我有一个函数,可以通过串口一次一个字节地读入一个字符。收集这些字节后,将它们传递给处理字节和消息的方法。
我知道如何解决这个问题(修复在下面),但为什么我不执行修复时我的字节会被截断?
unsigned char dpBuf[255];
...
// Pretend dpBuf has values 0x01 0x02 0x03 0x00 0x00 0x00 0x04 0x05
..
ProcessMsg(dpBuf);
..
void ProcessMsg(unsigned char *buff)
{
// buff comes in as 0x01 0x02 0x03 0x00 and rest is truncated
char p[255];
...
for (int i = 0; i < sizeof(buff); i++)
{
sprintf(p, " 0x%X ", (unsigned char)b[i]);
}
..
}
修复:
ProcessMsg((unsigned char*)&dpBuf, length); // instead of sizeof() in the loop, use length
..
void ProcessMsg (unsigned char *buff, int length)
{
// buff comes in as the original character string and is not truncated
..
// do for loop, print out contents
}
最佳答案
buff
声明为const char*
,所以sizeof(buff)
返回的是这样一个指针的大小,好像是4字节在你的机器上。因此,缓冲区的前四个字节将在循环中打印出来。
dpBuf
被声明为更大尺寸的数组并不重要,因为它作为指针传递给函数。要避免此问题,您应该向函数中添加一个参数,在该函数中显式传递缓冲区的大小。
关于c++ - 关于为什么字符串在\0的第一个实例上被截断的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051462/