I'm new with all the C programming and I have a question ,
If I have a struct for example - and I'm pointing on it , I want to create a new pointer in order to point on the same data , but not for the two pointers to point on the same object . how can I do that without copying every single field in the struct ?
typedef struct
{
int x;
int y;
int z;
}mySTRUCT;
mySTRUCT *a;
mySTRUCT *b;
a->x = 1;
a->y = 2;
a->z = 3;
and now I want b to point on the same data
b = *a
it's not correct, and the compiler is yelling at me
any help would be great! thank you :)
First thing, you code is incorrect. You create a pointer named a
, but you don't create anything for it to point to. You aren't allowed to dereference it (with a->x
) until it points to something.
Once you actually have some structs for your pointers to point to, then you can copy them by assignment:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With