我有一个带有一个structnamed示例的程序,它包含2个 int 成员和一个 char *。当创建2个名为 a 和 b 的对象时,我尝试用指针为 a 分配一个新的动态字符串,然后将所有值复制到< EM> b'/ em>的。所以 b = a 。但是稍后当尝试对 a 进行更改时:a.ptr[1] = 'X';
b 中的指针也会发生变化。我想知道为什么,以及如何解决这个问题。
struct Sample{
int one;
int two;
char* sPtr = nullptr;
};
int _tmain(int argc, _TCHAR* argv[])
{
Sample a;
Sample b;
char *s = "Hello, World";
a.sPtr = new char[strlen(s) + 1];
strcpy_s(a.sPtr, strlen(s) + 1, s);
a.one = 1;
a.two = 2;
b.one = b.two = 9999;
b = a;
cout << "After assigning a to b:" << endl;
cout << "b=(" << b.one << "," << b.two << "," << b.sPtr << ")" << endl << endl;
a.sPtr[1] = 'X' ;
cout << "After changing sPtr[1] with 'x', b also changed value : " << endl;
cout << "a=(" << a.one << "," << a.two << "," << a.sPtr << ")" << endl;
cout << "b=(" << b.one << "," << b.two << "," << b.sPtr << ")" << endl;
cout << endl << "testing adresses for a and b: " << &a.sPtr << " & b is: " << &b.sPtr << endl;
return 0;
}
答案 0 :(得分:3)
您的结构包含char*
。当您将a中的所有值分配给b时,也会复制指针。
这意味着a和b现在指向相同的char数组。因此,更改此char数组中的值会更改两个结构。
如果您不想这样做,请为b创建一个新的char数组并使用strcpy
。
答案 1 :(得分:2)
您正在复制指针而不是值。要解决此问题,您可以覆盖结构中的赋值运算符:
struct Sample{
int one;
int two;
char* sPtr = nullptr;
Sample& operator=(const Sample& inputSample)
{
one = inputSample.one;
two = inputSample.two;
sPtr = new char[strlen(inputSample.sPtr) + 1];
strcpy (sPtr, inputSample.sPtr);
return *this;
}
};