0

I am trying to create a copy of a std::string to a char*. This is my function and its 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 am unsure if a copy has been created or both of them are pointing to the same location. How to confirm this?

4

1 回答 1

2

您只是在复制地址并在 C++ 中使用 C强制转换,而是使用strdup

char* test2;
test2 = strdup(test1.c_str()); //free it after

或者

   char *test2 = malloc(test1.size());
   strcpy(test2, test1.c_str());
于 2013-07-31T06:01:38.633 回答