1

我有一个用十六进制数字填充的数组(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 多行代码,所以我提供的应该足以编译和运行。

4

1 回答 1

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]);
于 2014-09-03T21:13:55.033 回答