简体   繁体   中英

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++.

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 - } )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM