c++ - 使用struct中的指针来更改数据

标签 c++ struct

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

最佳答案

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

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

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

关于c++ - 使用struct中的指针来更改数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27534499/

相关文章:

c++ - Omnet 和 Inet 链接错误 : undefined reference to typinfo

c++ - vtk c++ 从 contourfilter 更新轮廓

c++ - 具有结构数据类型的链表

C++甚至更通用的运算符模板

如果在头文件中定义映射,则需要 C++ include 语句

c++ - 按地址访问结构中的元素

c - 我在链表的末尾创建一个垃圾节点只是为了指定 NULL。我怎样才能修改我的代码来防止这种情况发生?

c - 使用结构和 malloc 时为 "error: conversion to non-scalar type requested"

struct - 是否有可能有一个结构包含对生命周期比结构短的值的引用?

c++ - C++ 模板中的非法间接寻址