How to duplicate a pointer to point to the same object

I am new to C programming and I have a question,

If I have a structure, for example, and I point to it, I want to create a new pointer to point to the same data, but not for two pointers pointing to the same object. How can I do this without copying each individual field in the structure?

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 to the same data

 b = *a 

this is not correct and the compiler yells at me

any help would be wonderful! thanks:)

+6
source share
2 answers

Firstly, the code is incorrect. You create a pointer named a , but you do not create anything to indicate it. You are not allowed to play it (with a->x ) until it points to something.

Once you actually have some structures for the pointers that you want to specify, you can copy them on 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 
+10
source

The memcpy() function copies a block of data from one place to another. To fit your question, you must do:

 memcpy(b, a, sizeof(*b)); 
+1
source

Source: https://habr.com/ru/post/920028/


All Articles