Search code examples
c++stringvisual-studio-2008multidimensional-arraymemcpy

Array of strings in C++: Extra characters printed


I am having some trouble understanding this output for my code:

#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;

Actual Output:

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

Expected Output:

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

Why are the extra characters being printed at the end of pipeNames[0]. I am using string::c_str() which automatically appends null character, so why the error?


Solution

  • You're not copying the null char. strlen does not count the null char. Try this

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

    No need for your casts either. Casts are dangerous, because they can mask compiler errors so don't use them if you don't need them.