将带符号的 char 数组传递给期望 const char 指针的函数会导致乱码数组值

Passing a signed char array to function expecting const char pointer results in garbled array value

我似乎无法理解这里发生的事情:

我有一个函数可以计算两个日期之间的秒数差异。然后它被移位以产生一些输出:

void GetUTC(unsigned char buffer[5])
{
    struct tm str_time;
    time_t start;
    time_t current = time(NULL);
    str_time.tm_year = 2010 - 1900;
    str_time.tm_mon = 1;
    str_time.tm_mday = 1;
    str_time.tm_hour = 0;
    str_time.tm_min = 0;
    str_time.tm_sec = 0;
    str_time.tm_isdst = 0;
    start = mktime(&str_time);

    printf("%s\n",ctime(&start));
    printf("%s\n\n",ctime(&current));

    uint32_t someInt = difftime(current,start);
    buffer[0] = 2;
    buffer[1] = (someInt & 0xff);
    someInt = someInt >> 8;
    buffer[2] = (someInt & 0xff);
    someInt = someInt >> 8;
    buffer[3] = someInt;
    someInt = someInt >> 8;
    buffer[4] = (10 & 0xff);
}

我给它这个数组:

    unsigned char toWrite[5];

然后调用它

    GetUTC(toWrite);

一切顺利。现在我有一个函数,我正在尝试将新数组输入其中,它采用以下参数:

void gatt_write_attribute(GDBusProxy *proxy, const char *arg)

我这样称呼它:

gatt_write_attribute(someProxy, toWrite);

但是我传递给函数 gatt_write_attribute 的数组显示它是混乱的垃圾:023\n23 而不是我期望的 toWrite 值。 (数字不同,因为它与时间有关):

[0]: 2
[1]: 23
[2]: 54
[3]: 128
[4]: 10

我尝试在 toWrite 的末尾添加终止符 [=18=],但它没有改变任何东西。我尝试将其转换为 const char 指针,但也没有用。

我觉得我错过了一个非常简单的细节。有人可以解释为什么我不能将此 char 数组传递给 gatt_write_attribute 函数吗?

您需要将数组作为指针传递给第一个函数。否则它只是被复制到堆栈并且函数写入新副本。垃圾可能在那里,因为它还没有被初始化。

正如 Ian Abbott and Chux 在对我的原始问题的评论中指出的那样,我确实很傻,没有意识到我的调试器正在将所指向的东西显示为字符数组而不是数字。这就是导致乱码的原因。

我可能应该让自己在工作时间多睡一会儿。