[英]Using pointers in struct to change data
我有一個帶有一個structnamed示例的程序,它包含2個int成員和一個char *。 當創建2個名為a和b的對象時,我嘗試使用指針為a分配一個新的動態字符串,然后將所有值復制到b 。 所以b = 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;
}
您的結構包含一個char*
。 當您將a中的所有值分配給b時,指針也會被復制。
這意味着a和b現在指向相同的char數組。 因此,更改此char數組中的值會同時更改兩個結構的值。
如果不想這樣做,請為b創建一個新的char數組,然后使用strcpy
。
您正在復制指針而不是值。 為了解決這個問題,您可以在結構中覆蓋您的賦值運算符:
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;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.