Search code examples
cpointersstructmallocdereference

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.

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.