class CStrok { public: char* m_pstr; }; void main() { CStrok a; CStrok b; a.m_pstr = new char[4]; a.m_pstr = "one"; b = a; b.m_pstr = "two"; cout << b.m_pstr << endl; cout << a.m_pstr << endl; return; } 

If I correctly understood the pointers, then when b = a, the address of the string "one" is copied from variable a into variable b, and when a different string is assigned to pointer b, the string in a must also change. and the pointers to variables a and b point to the same address. However, when strings are output, they are different. What's wrong ?

    2 answers 2

    You have a memory leak in the program. See - here you allocated 4 bytes somewhere in memory and passed a pointer to a.m_pstr :

     a.m_pstr = new char[4]; 

    And then they successfully rewrote it with the address of the string "one" , i.e. The first pointer lost, and you will never release it.

     a.m_pstr = "one"; 

    By the way, if you wanted to copy a string to the allocated memory, you had to use something like strcpy . And yet - note that the string literal is constant , so you should not change it, for example, you cannot write a.m_pstr[0] = 'q' .

     b = a; 

    You just copied the address from the variable in a to b . They now point to the same line.

     b.m_pstr = "two"; 

    And now the variable a stores the old address, and the variable b gets the address of the string "two" . Therefore, when outputting, you output two different lines.

      If I understand pointers correctly, then when b = a, the address of the string "one" is copied from variable a into variable b

      Right

      and when assigning a different string to pointer b, the string in a should also change because and the pointers to variables a and b point to the same address.

      No, after assigning another string, a and b now point to different addresses. If they pointed to the same address, and you would change the value of the object at the address, then both in a and in b would change - after all, the same object.

      However, when strings are output, they are different. What's wrong ?

      All right