Hi guys,
Since I'm a newbie in C programming I want some suggestions with the interpretation for the pointer usage. So I have the following piece of code (is not my implementation). What I don't understand here is why it is is used the expression "*p = n; "?
As long as I know if I call the function with list_add(&n,1) means that I transfer the address of the node "n" to the function list_add.
Now it means that *p = &n or *p = n (this are similar construction). This means if &n=0x030402ff ----> *p = 0x030402ff. Right?
What I don't understand is why if I comment line " *p = n; " the value from *p is always 0x0 (the address of the NULL element).
typedef struct ns {
int data;
struct ns *next;
} node;
node *list_add(node **p, int i) {
/* some compilers don't require a cast of return value for malloc */
node *n = (node *)malloc(sizeof(node));
if (n == NULL)
return NULL;
n->next = *p;
*p = n; <<--------------------------?????
n->data = i;
return n;
}
int main(void) {
node *n = NULL;
list_add(&n, 0); /* list: 0 */
list_add(&n, 1); /* list: 1 0 */
return 0;
}
Sorry for bugging you with this simple questions.
Thanks in advance