use*_*966 7 c struct pointers duplicates
我是所有C编程的新手,我有一个问题,
如果我有一个结构例如 - 我指向它,我想创建一个新的指针,以指向相同的数据,但不是指向同一个对象的两个指针.如何在不复制结构中的每个字段的情况下执行此操作?
typedef struct
{
int x;
int y;
int z;
}mySTRUCT;
mySTRUCT *a;
mySTRUCT *b;
a->x = 1;
a->y = 2;
a->z = 3;
Run Code Online (Sandbox Code Playgroud)
现在我希望b指向相同的数据
b = *a
Run Code Online (Sandbox Code Playgroud)
它不正确,编译器对我大吼大叫
任何帮助都会很棒!谢谢 :)
Ste*_*sop 10
首先,你的代码是不正确的.您创建一个名为的指针a
,但您没有创建指向它的任何内容.a->x
在指向某事之前,您不得将其取消引用(with ).
一旦你实际拥有指向指针的一些结构,那么你可以通过赋值复制它们:
myStruct a_referand = {0};
myStruct b_referand = {0};
myStruct *a = &a_referand;
myStruct *b = &b_referand;
a->x = 1;
*b = *a; // copy the values of all members of a_referand to b_referand
// now b->x is 1
b->x = 2;
// now b->x is 2 but a->x is still 1
Run Code Online (Sandbox Code Playgroud)