balexios balexios - 1 year ago 61
C++ Question

Array Of Char Pointers initialization strange behaviour

Yesterday I came across a strange behavior in c++ in case of an array of char pointers.

Here is the code example:

int main() {
char *args[] = {(char *) std::to_string(12345).c_str(), (char *) std::to_string(12346).c_str()};
printf("%s %s\n", args[0], args[1]);

return 0;

And the output is:

12346 12346

I suppose that the answer should be "12345 12346". Any help?
My only compile flag is -std=c++11 and I use g++.

Answer Source

These strings you've created are temporaries, you're creating pointers to their c_str and then destroying them. The contents of the pointers will be junk.

EDIT: Thanks to Barmar for suggesting adding a correction.

int main() 
  std::string string1 = std::to_string(12345);
  std::string string2 = std::to_string(12346);

  const char *args[] = {string1.c_str(), string2.c_str()};
  printf("%s %s\n", args[0], args[1]);
  return 0;

In this code the named std::strings won't be destroyed until the end of the scope (at the close of the curly brackets - } )