C++ copy const char* to char*

leon22 picture leon22 · Jun 13, 2012 · Viewed 17.7k times · Source

I have a function

ClassA::FuncA(const char *filePath)

and want to copy this const char string* to a char*!

My solution:

char *argv[2];
int length = strlen(filePath);
argv[1] = new char(length +1);
strncpy(argv[1], filePath, length); 

after this I have in argv[1] the desired chars but also some other undefined chars!

filePath:

"C:\Users\userA\Parameter.xmlþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþKŸQyá•"

Whats wrong here? The length with strlen is OK!

Answer

Luchian Grigore picture Luchian Grigore · Jun 13, 2012

Like so:

argv[1] = new char[length +1](); // () to value-initialize the array

Your version:

argv[1] = new char(length +1);

only allocates a single char and value-initializes it to length+1.