Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to duplicate pointer in order to point on the same object

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 :)

like image 461
user1386966 Avatar asked Jul 09 '12 11:07

user1386966


1 Answers

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
like image 136
Steve Jessop Avatar answered Sep 19 '22 19:09

Steve Jessop