-1

我正在使用 micropython 中的 C 模块...如果我将字节数组传递给函数,则只有前 8 个字节会成功(根据 sizeof)。我还必须发送长度,然后复制它以访问函数中的所有内容。

static void printSomeBytes(char *description, byte *bytes)
{    
    printf("\r\n%s: ", description);
    for (int i = 0; i < sizeof(bytes); ++i )
    {
        printf("%02X", bytes[i]); 
    }
}

static void printAllBytes(char *description, byte *bytes, int length)
{    
    byte copy[length];
    memcpy(copy, bytes, length);

    printf("\r\n%s: ", description);
    for (int i = 0; i < sizeof(copy); ++i )
    {
        printf("%02X", copy[i]); 
    }

    // this also works without making a copy 
    //for (int i = 0; i < length; ++i )
    //{
    //    printf("%02X", bytes[i]); 
    //}
}

byte Kifd[] = { 0x0B, 0x79, 0x52, 0x40, 0xCB, 0x70, 0x49, 0xB0, 0x1C, 0x19, 0xB3, 0x3E, 0x32, 0x80, 0x4F, 0x0B};

printSomeBytes("Kifd", kifd); // prints "Kifd: 0B795240CB7049B0"
printAllBytes("Kifd", kifd, sizeof(kifd)); // prints "Kifd: 0B795240CB7049B01C19B33E32804F0B"

我在做什么错/有没有更好的方法将指向字节数组的指针发送到函数?

4

2 回答 2

3

你在解释问题方面做得很差。你是说sizeof(bytes)返回8?

bytes是一个指针,并sizeof(bytes)返回该指针的大小。在您的系统上,指针可能是 8 个字节。这与它指向的地址的字节数无关。

在 C 中,当您获得一个指针时,除非您将该信息作为另一个参数提供或在数据中具有特殊的终止值,否则无法知道它指向多少字节。

于 2018-01-30T23:17:21.087 回答
3

sizeof(bytes)返回指针byte需要存储在内存中的字节数。它不会返回您指向的数组所bytes包含的字节数。

为此,您需要将该大小传递给函数:

static void printSomeBytes(char *description, byte *bytes, size_t size)
{
    printf("\r\n%s: ", description);
    for (size_t i = 0; i < size; ++i )
    {
        printf("%02X", bytes[i]); 
    }

    puts("");

}

编辑
我还在puts("")那里添加,以便立即打印字节。请注意,它printf是缓冲的,它不会在屏幕上显示输出,除非您fflush(stdout);手动刷新它()或'\n'printf. puts(string)等效于printf("%s\n", string);但没有必须解析格式参数的开销。
结束编辑

然后调用它:

byte Kifd[] = { 0x0B, 0x79, 0x52, 0x40, 0xCB, 0x70, 0x49, 0xB0, 0x1C, 0x19, 0xB3, 0x3E, 0x32, 0x80, 0x4F, 0x0B};

printSomeBytes("Kifd", Kifd, sizeof Kifd / sizeof *Kifd);

获取数组元素数量的正确方法是:

sizeof array / sizeof *array

即使您知道该类型是 8 位长,我也鼓励您使用该公式。它使代码更具可移植性。

于 2018-01-30T23:19:38.953 回答