This a follow up from this question: Why does a function which returns void not hold value?. A user indeed suggested me to draw the pointers in the function struct node * insert_front
and so the main questions is about that function and this line of code head = new
This is the minimum code needed:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
struct node* init(int value) {
struct node* head = malloc(sizeof(struct node));
if (!head) return NULL;
head->value = value;
head->next = NULL;
return head;
}
void insert_back(struct node* head, int value) {
if (!head) return;
struct node* temp = head;
struct node* new = malloc(sizeof(struct node));
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new;
new->value = value;
new->next = NULL;
return;
}
struct node* insert_front(struct node* head, int value) {
struct node* new = (struct node*)malloc(sizeof(struct node));
new->value = value;
new->next = head;
printf("head->value: %d\n", head->value);
printf("head->value ptr: %p\n", &head->value);
printf("new->value: %d\n", new->value);
printf("new->value ptr: %p\n", &new->value);
head = new;
printf("head->value: %d\n", head->value);
printf("head->value ptr: %p\n", &head->value);
printf("new->value: %d\n", new->value);
printf("new->value ptr: %p\n", &new->value);
return new;
}
int main() {
struct node* head = init(5);
insert_back(head, 7);
insert_back(head, 9);
insert_back(head, 12);
head = insert_front(head, 999)
return 1;
}
The output produced from struct node* insert front(...)
is
// after, new->next = head
head->value: 5
head->value ptr: 0x(...)9e0
new->value: 999
new->value ptr: 0x(...)a50
// after, head = new
head->value: 999
head->value ptr: 0x(...)a50
new->value: 999
new->value ptr: 0x(...)a50
So we see that after head = new
we have the same addresses for head
and new
. Given this I have two questions.
Firstly, have I understood correctly that, after head = new
what happens is that we have moved the pointer which was pointing to the start of that region of memory used by the linked list (that is from head
) to a new place in memory (that is where new
is in memory)? Otherwise (or more technically, well-explained) what happened?
Secondly, when I print:
printf("&head->value: %p\n", &head->value);
printf("&head: %p\n", &head);
printf("head: %p\n", head);
I obtain
&head->value: 0x(...)9e0
&head: 0x(...)8c8
head: 0x(...)9e0
So, with head
I am accessing the address of the region of memory I am pointing to and with &head
the address of the pointer itself. But then why with &head->value
I am accessing the same as with head
?