The program doesn't have a specific function; I am just currently studying lists and I have a hard time understanding why I don't get a compile error in line where Node *curr = *root; Shouldn't I initialize Node *curr with an address using &? But when I set a double pointer and a pointer and I initialize the second one with *p, where p is the double pointer, I get a compile error and the program doesn't even run. Both scenarios seem the same to me, and I can't see the difference.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int x;
struct Node *next;
} Node;
void insert_end(Node **root, int value) {
Node *new_node = malloc(sizeof(Node));
new_node->next = NULL;
new_node->x = value;
//We have to use the loop to reach the
// end of the list where we add our additional box
Node *curr = *root;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = new_node;
}
int main() {
Node *root = malloc(sizeof(Node));
root->x = 15; //1o element
root->next = NULL;
//the last element of a list is always initialized with null
//exit loop when *next = NULl
//it matters the order of freeing the memory
insert_end(&root, -2);
for (Node *curr = root; curr != NULL; curr = curr->next) {
printf("%d\n", curr->x);
}
return 0;
}
Leta give these things values for clarity.
In
main()lets say the stack starts at address 100000. Local variablerootis allocated there, so its address is 1000000.malloc()returns something from the heap, lets say it's address 100, sorootcontains 100.You call
insert_end(), the parameters are put on the stack, so there's a new version ofrootlocal toinsert_end(). Saymain()needed a total of 8 bytes for local storage, and stack storage is extended downward (decreasing addresses) so the parameters forinsert_end()are allocated at addresses 99992 (first parameterroot) and 99988 (second parametervalue).rootinmain()androotininsert_end()are different variables with different contents. The content ofrootininssert_end()is the address ofrootinmain(), which is 100000.Down below, you're assigning
*roottocurr, so you're following the address 100000 inrootininsert_end()torootinmain()and taking that value - 100. You're assigning 100 intocurr, socurrreferences the memory you originally got frommalloc().To understand better, consider the type of
rootisNode **, when you add a*to a pointer variable, you remove it from the type, so*rootis of typeNode *, and that's the same asNode *curr.