How to convert string to char array in C++?

Simplest way I can think of doing it is:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

For safety, you might prefer:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

or could be in this fashion:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());

Leave a Comment