nsane
nsane

Reputation: 1765

Accessing structure elements via double pointers in C

I'm implementing linked lists using structures. I have a structure -

typedef struct llist node;
typedef node *nodeptr;
struct llist
{
    int data;
    nodeptr next;
};

Now lets say I declare a variable nodeptr *ptr;. How do I access the members data and next using ptr?

Upvotes: 4

Views: 5209

Answers (1)

KARTHIK BHAT
KARTHIK BHAT

Reputation: 1420

You deference the first pointer and then the second one.

To access the data and next in the structure statement would like this

(*ptr)->data = 5;
(*ptr)->next = temp;

brackets around ptr is required since -> has higher priority than *.

-> is equivalent to writing *. (e.g. ptr->data is the same as *ptr.data).

Upvotes: 7

Related Questions