c++ - Copying a std::string to char* -
this question has answer here:
i trying create copy of std::string char*. function , seen result:
void main() { std::string test1; std::cout << "enter data1" << std::endl; std::cin >> test1; char* test2; test2 = (char*)test1.c_str(); std::cout << "test1: "<< &test1 << std::endl; std::cout << "test2: "<< &test2 << std::endl; } enter data1 check test1: 0x7fff81d26900 test2: 0x7fff81d26908
i unsure if copy has been created or both of them pointing same location. how confirm this?
you copying adress , using c cast in c++ use strdup instead
char* test2; test2 = strdup(test1.c_str()); //free after
or
char *test2 = malloc(strlen(test1.c_str())); strcpy(test2, test1.c_str());
Comments
Post a Comment