c++ - Array Of Char Pointers initialization strange behaviour -


yesterday came across strange behavior in c++ in case of array of char pointers.

here 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 output is:

12346 12346  

i suppose answer should "12345 12346". help? compile flag -std=c++11 , use g++.

these strings you've created temporaries, you're creating pointers c_str , destroying them. contents of pointers junk.

edit: barmar suggesting adding 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 code named std::strings won't destroyed until end of scope (at close of curly brackets - } )


Comments