Rudrani Angira Rudrani Angira - 1 year ago 77
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.

Answer Source

-> 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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download