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?

BlueBottle
  • 35
  • 1
  • 8
  • 1
    Please be noted, test1 is a class, test2 is a pointer, it's totally different. test1.c_str() return the pointer of the member of test1. Alexis's answer is correct way to copy whole data to a new pointer. – Yigang Wu Jul 31 '13 at 06:05

1 Answers1

2

You are just copying the adress and using a C cast in C++ use strdup instead

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

or

   char *test2 = malloc(test1.size());
   strcpy(test2, test1.c_str());
Marc J. Schmidt
  • 8,302
  • 4
  • 34
  • 33
Alexis
  • 2,149
  • 2
  • 25
  • 39