在结构中使用指针来更改数据
Using pointers in struct to change data
>我有一个程序,其中包含一个结构命名的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;
}
};
相关文章:
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 如何在没有数据拷贝的情况下从指针创建一个Eigen VectorXd对象
- 如何使用数据对象上的常量指针初始化类
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 将矢量的数据复制到<MyStruct>矢量<MyStruct>的指针
- 使用指针访问数组中的对象数据成员
- CURLOPT_INTERLEAVEFUNCTION回调函数始终接收 nullptr 作为用户数据指针
- C++中纹理数据指针的联合
- 什么是成员数据指针的正确赋值语句
- EIGEN地图 - 它是否占数据指针的所有权
- C 11 STD :: Promise返回STD :: String从线程中返回String,数据指针看起来已复制
- 为什么函数指针和数据指针在 C/C++ 中不兼容
- 带有数据指针的可变模板模板
- 为什么我在尝试将opencv图像数据指针转换为char*时出错
- 通过在CGAL中传递高度、宽度、深度和数据指针来创建Image_3实例
- read() 缓冲区有无效数据(指针问题?
- 在用SWIG编译的c和lua模块之间共享数据指针
- 具有原始数据指针和刻字的对象
- 对openCV的数据指针进行类型转换
- Lua用户数据指针的生存期