I normally program in python. To increase performance of my simulations, I am learning C. I have a problem to understand the use of a pointer of a pointer when implementing the append function to a linked list. This is an excerpt of the code from my book (Understanding Pointers in C by Kanetkar).
#include <stdlib.h>
#include <stdio.h>
struct node{
int data;
struct node *link;
};
int main(){
struct node *p; //pointer to node structure
p = NULL; //linked list is empty
append( &p,1);
return 0;
}
append( struct node **q, int num){
struct node *temp, *r; //two pointers to struct node
temp = *q;
if(*q == NULL){
temp = malloc(sizeof(struct node));
temp -> data = num;
temp -> link = NULL;
*q = temp;
}
else{
temp = *q;
while( temp -> link != NULL)
temp = temp -> link;
r = malloc(sizeof(struct node));
r -> data = num;
r -> link = NULL;
temp -> link = r;
}
}
In this code, I pass the double pointer **q to the append function. I get that this is the adress of the address, i.e. the adress of NULL in this case.
I just don't get why one does it like this. Would it not be valid to remove one * operator from everything in the append() function and simply pass the adress of NULL (i.e. p instead of &p) to the append() function?
I have googled this question. The answers are either too hard to understand (since I'm just a C beginner) or too plain. I'm thankful for any hints, comments or links where I can read up about this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…