char数组末尾的怪异字符

时间:2012-01-20 09:00:54

标签: c++ arrays char smart-pointers

我想要做的是从缓冲区数组中读取字符

std::vector<char> SmartIO::PeekChar(){
        int newlen= 0;
        while(buffer[ptrSeek] != 0){
            ptrSeek++;
            newlen++;
        }

        std::vector<char> temp(newlen);
        memcpy(temp.data(),&buffer[ptrSeek-newlen],newlen);
        ptrSeek = 0;
        return temp;
}

所以temp.data()会返回methodtest‎‎‎‎««««««««î‏,而结果应仅为methodtest! 是什么导致了这种奇怪的角色?

2 个答案:

答案 0 :(得分:1)

您的缓冲区/字符数组不以空值终止。

您必须知道缓冲区的长度,或者必须以null结尾。

答案 1 :(得分:0)

注意:

你不能像那样使用shared_ptr,因为它会调用错误的删除。它需要调用delete []。

您可以使用自定义删除工具或boost::shared_array<char>

进行调整

除此之外,要从字符数组打印,它需要一个空终止符。你也需要为它分配一个字节,你可以使用strcpy。

如果你想复制它几次并避免重新分配,我只会使用shared_array,否则我只会使用std::vector<char>std::string(前者如果你想要一个可写数组字符)。

相关问题