c++ - 关于为什么字符串在\0的第一个实例上被截断的问题

标签 c++ pointers

我有一个函数,可以通过串口一次一个字节地读入一个字符。收集这些字节后,将它们传递给处理字节和消息的方法。

我知道如何解决这个问题(修复在下面),但为什么我不执行修复时我的字节会被截断?

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/

相关文章:

c++ - 调试简单控制台程序的问题::CLion

c++ - 解码 Opus 音频数据

c++ - 书籍索引,如何查看每个单词并根据其首字母存储

c++ - 函数不能用作 'constexpr' 函数

c++ - 迭代 char** 为什么这行得通?

c - 删除资源

c++ - 嵌套 C++ 模板的一个例子

c++ - const char myStr[] = "hello"和 const char* myStr = "hello"有什么区别

c++ - C++内存地址的奇怪现象

c++ - 复制具有巨大数组成员的类时是否使用指针?