Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C, does assigning a struct to a struct pointer assigns a copied value of the struct?

I just started learning C so pardon me if the nomenclature is incorrect.

If I assign a struct to a struct pointer and then change values of struct, it’s not reflected when I try to access the value from struct pointer.

struct Node_int *new_node_address = (struct Node_int *) malloc(sizeof(struct Node_int));
struct Node_int new_node_instance;
*new_node_address = new_node_instance;
new_node_instance.data = data;
new_node_instance.next= NULL;
printf("%d", new_node_address->data)

Here printf("%d", new_node_address->data) will return a garbage value but same print statement in following code will return correct/assigned data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct Node_int *new_node_address = (struct Node_int *) malloc(sizeof(struct Node_int));
struct Node_int new_node_instance;
new_node_instance.data = data;
new_node_instance.next= NULL;
*new_node_address = new_node_instance;
printf("%d", new_node_address->data)

I want to understand why this is happening. Does *new_node_address gets the copied value of new_node_instance in the memory?

>Solution :

I want to understand why this is happening. Does *new_node_address gets the copied value of new_node_instance in the memory?

Yes, it does, there is a copy, the dereference operator * means you are copying data to the memory address which is pointed by new_node_address. Which is the memory block returned by malloc.

If you want to make the pointer point to the address of the declared new_node_instance, you’d need:

new_node_address = &new_node_instance;

In this case no copy takes place and for that reason you also don’t need to allocate memory, you are making the pointer point to a variable which already has memory storage.

The reason why the second code snippet works is because you make the copy after you assign the data, as opposed to the first code snippet.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading