c - 将有符号的 char 数组传递给需要 const char 指针的函数会导致数组值出现乱码

标签 c arrays parameters char parameter-passing

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

我有一个函数可以计算两个日期之间的差异(以秒为单位)。然后它会进行位移以产生一些输出:

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 的数组显示它是困惑的垃圾:$2\20023\n23 而不是我期望的 toWrite 值。 (数字有所不同,因为它与时间有关):

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

我尝试在 toWrite 的末尾添加终止 \0,但它没有改变任何内容。我尝试将其转换为 const char 指针,但这也不起作用。

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

最佳答案

正如 Ian Abbott 所指出的和 Chux在对我原来问题的评论中,我确实很愚蠢,没有意识到我的调试器将所指向的内容显示为字符数组而不是数字。这就是导致乱码的原因。

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

关于c - 将有符号的 char 数组传递给需要 const char 指针的函数会导致数组值出现乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33696167/

相关文章:

C无法使用变量打开文件

c - IGMPv2 数据包上的路由器警报选项

asp.net - 动态设置 DataFormWebPart 中 ParameterBinding 的 DefaultValue

java - 比较java中的两个列表

postgresql - 我可以让 plpgsql 函数在不使用变量的情况下返回一个整数吗?

parameters - TeamCity 条件参数值

c - 程序在输入输入之前结束(开关盒)

c - 交换 C 变量

arrays - 如何检查对象是否存在于 Angular 中的对象数组中

c++ - C++中特殊数组的问题