c++ - How to get string data back using pointer? -
i can not string data using pointer char array. give me explanation doing wrong please.
#include "stdafx.h" #include <conio.h> #include <string> using namespace std; string getstring() { return string("255"); } int _tmain(int argc, _tchar* argv[]) { char* str_p = const_cast<char*>(getstring().c_str()); printf("pointer : %s\n", str_p); string str; str = str_p[0]; str += str_p[1]; str += str_p[2]; printf("constructed : %s\n", str.c_str()); _getch(); return 0; }
the console output :
pointer : constructed :
there lot wrong line:
char* str_p = const_cast<char*>(getstring().c_str());
getstring()
returns temporary string
. gets destroyed @ end of line. end dangling pointer internal data deallocated. furthermore, const_cast
should ever using if really really need - editing data directly asking trouble.
if want pointer string, right thing is:
string old = getstring(); // make sure doesn't go out of scope const char* str_p = old.c_str(); // while pointer around
Comments
Post a Comment