简体   繁体   English

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

[英]Using pointers in struct to change data

I have a program with one structnamed sample, it contains 2 int members and one char *. 我有一个带有一个structnamed示例的程序,它包含2个int成员和一个char *。 when creating 2 objects called a and b , I try assign a new dynamic string to a with the pointer and then copy all the values to b . 当创建2个名为ab的对象时,我尝试使用指针为a分配一个新的动态字符串,然后将所有值复制到b so b = a . 所以b = a But later on when try to make changes to a like this : a.ptr[1] = 'X'; 但后来当尝试进行更改如下: a.ptr[1] = 'X'; the pointer in b also changes. b中的指针也会更改。 I want to know why, and how can I solve this. 我想知道为什么,以及如何解决这个问题。

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;
}

Your struct contains a char* . 您的结构包含一个char* When you assign all values in a to b, the pointer is also copied. 当您将a中的所有值分配给b时,指针也会被复制。

This means that a and b now point to the same char array. 这意味着a和b现在指向相同的char数组。 Therefore changing a value in this char array changes it for both structs. 因此,更改此char数组中的值会同时更改两个结构的值。

If you do not want this, make a new char array for b and use strcpy . 如果不想这样做,请为b创建一个新的char数组,然后使用strcpy

You are copying the pointer not the value. 您正在复制指针而不是值。 To solve this you could override your assignment operator in the structure: 为了解决这个问题,您可以在结构中覆盖您的赋值运算符:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM