我在理解我的代码的输出时遇到了一些麻烦:

#define MAX 5

char pipeNames[MAX][1024];
string s1 = "\\\\.\\p\\p1";
string s2 = "\\\\.\\p\\p2";
int len1 = strlen(s1.c_str());
int len2 = strlen(s2.c_str());
memcpy((void*)pipeNames[0], (void*)s1.c_str(), len1);
memcpy((void*)pipeNames[1], (void*)s2.c_str(), len2);
cout<<pipeNames[0];
cout<<endl<<len1;
cout<<endl<<pipeNames[1];
cout<<endl<<len2;


实际输出:

\\.\p\p1É┼é|
8
\\.\p\p2
8


预期产量:

\\.\p\p1
8
\\.\p\p2
8


为什么在pipeNames [0]的末尾打印多余的字符。我正在使用自动附加空字符的string :: c_str(),为什么会出错?

最佳答案

您没有复制空字符。 strlen不计算空字符。尝试这个

memcpy(pipeNames[0], s1.c_str(), len1 + 1);
memcpy(pipeNames[1], s2.c_str(), len2 + 1);


也不需要您的演员。强制转换很危险,因为它们可以掩盖编译器错误,因此如果不需要它们,请不要使用它们。

关于c++ - C++中的字符串数组:打印额外的字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11700920/

10-11 01:23