在结构中使用指针来更改数据

Using pointers in struct to change data

本文关键字:数据 指针 结构      更新时间:2023-10-16

>我有一个程序,其中包含一个结构命名的sample,它包含2个int成员和一个char *。 当创建 2 个名为 a 和 b 的对象时,我尝试使用指针a 分配一个新的动态字符串,然后将所有值复制到 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;
    }
};