【问题标题】:Using pointers in struct to change data在结构中使用指针来更改数据
【发布时间】:2014-12-17 20:42:36
【问题描述】:

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

【问题讨论】:

  • 你能发布运行这个代码片段的输出吗?
  • b赋值给a后,b的所有成员的值都是a中的值的副本,包括指针(指针也是值,只是发生可解释为地址)。所以ab 都有指向内存中相同位置的指针——并且更改该内存与ab 无关,因为它们的所有指针都只是指向那个(相同) 地点。这有帮助吗?
  • What is The Rule of Three? 的可能重复项

标签: c++ struct


【解决方案1】:

您的结构包含char*。当您将 a 中的所有值分配给 b 时,指针也会被复制。

这意味着 a 和 b 现在指向同一个 char 数组。因此,更改此 char 数组中的值会更改两个结构的值。

如果您不希望这样,请为 b 创建一个新的 char 数组并使用 strcpy

【讨论】:

  • 我更愿意建议使用std::string 而不是这个。使用这样的数组可能是有原因的,但这是低级编程,如果人们仍在努力使用 C++ 对象模型,则不应尝试。
  • 同意,如果作者要使用 C++ 对象模型。代码片段结合了 C 和 C++。
  • OP 没有使用 OO 方法,因此不需要 std::string。
  • 我无法理解你的推理,@2501。即使您的程序不需要任何 OOP,您仍然可以从使用更高级别的数据类型(如 std::string)中受益。
【解决方案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;
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多