Rudrani Angira Rudrani Angira - 7 months ago 32
C Question

Pointers to pointers : error in referencing members

Below is a simple code where I am trying to use pointers to pointers to add a node to a linked list.

#include <stdio.h>
#include <malloc.h>

struct node
int data;
struct node *next;

void insert(struct node **root)
struct node * temp = (struct node *)malloc(sizeof(struct node));
if(*root == NULL)
*(root) = (struct node *) malloc (sizeof(struct node ));
*(root)->data = 5;
*(root)->next = temp;

int main()
struct node *root = NULL;
return 0;

My understanding is that in main() a block is getting allocated to
. And in
the address of that memory block is passed in the argument. Then it checks if their is any memory block allocated to a structure at that address and if it is NULL memory is allocated to a structure block. And this should be referenced by
.But when I execute the above code I get the following error:

error: request for member 'data' in something not a structure or union

I am not able to understand where i am going wrong exactly.


-> binds tighter than the dereferencing operator (*). See operator precedence. So,

*(root)->data = 5;

is equivalent to:

*(root->data) = 5;

What you intended to do was:

(*root)->data = 5;

Same for the next line, which should be:

(*root)->next = temp;

Also, note that malloc.h is not portable. You should include C standard header stdlib.h> instead to get the prototype for malloc().