我有一个数组(readingreg [4]),它用十六进制数字填充。我的目标是将数据类型转换为字符串。我已经阅读了一些建议,似乎sprintf是要走的路。
这就是我的尝试:
sprintf(server0, "0x%02X", readingreg[0]);
printf("This is element 0: %s\n", server0);
sprintf(server1, "0x%02X", readingreg[1]);
printf("This is element 1: %s\n", server1);
sprintf(server2, "0x%02X", readingreg[2]);
printf("This is element 2: %s\n", server2);
sprintf(server3, "0x%02X", readingreg[3]);
printf("This is element 3: %s\n", server3);
printf("This is element 0: %s\n", server0);
printf("This is element 1: %s\n", server1);
printf("This is element 2: %s\n", server2);
printf("This is element 3: %s\n", server3);
这是我的输出:
This is element 0: 0x4A
This is element 1: 0xAA
This is element 2: 0xAA
This is element 3: 0xA0
This is element 0: 0
This is element 1: A0
This is element 2: xA0
This is element 3: 0xA0
此时,我对sprintf为我做了什么感到非常困惑。我的预期输出是server0-server4都保留了它们的字符串值。知道为什么会这样吗?
以下是该计划的简化版本:
readingreg[0] = 4A;
readingreg[1] = AA;
readingreg[2] = AA;
readingreg[3] = A0;
char server0[1];
char server1[1];
char server2[1];
char server3[1];
完整的程序超过1000行代码,所以我提供的代码应该足以编译和运行。
答案 0 :(得分:1)
当你这样做时:
char server0[1];
sprintf(server0, "0x%02X", readingreg[0]);
你试图将5个字符(不要忘记尾随'\ 0')放入1个字符的缓冲区中。这会导致未定义的行为,恰好会在观察到的输出中显示出来。
你应该做的(至少)是让字符缓冲区大到足以存储你放入的内容:
char server0[8];
sprintf(server0, "0x%02X", readingreg[0]);
更好的解决方案是使数组更大和使用snprintf()
或类似函数,以确保不会溢出字符缓冲区:
char server0[8];
snprintf (server0, sizeof(server0)/sizeof(server0[0]), "0x%02X", readingreg[0]);