2

I'm currently trying to implement a doubly linked list in C, and am not understanding how to access the struct from a double pointer.

Here is my simple struct:

typedef struct node {
  int val;
  struct node * next;
  struct node * prev;
} node;

Here is a simple method where I try to push a value to the front of the list:

void push_front(node ** head, int newVal) 
{
  node * newNode = malloc(sizeof(node));

  newNode->val = newVal;
  newNode->next = head;

  *head->prev = newNode;

  *head = newNode;
}

However, the line *head->prev = newNode gives me an error, saying that the left of ->prev must point to a struct/union. I'm just learning C so maybe I'm overlooking something really easy, but isn't head the pointer to the pointer of my head node? And *head is the pointer to my head node. Which I would assume means *head->prev should work?

2 Answers 2

6

Yes, head is a pointer to the pointer of your head node. So you can access ->prev by doing:

(*head)->prev = newNode;

Without the parentheses, the operator precedence rules of C parse your statement as

*(head->prev) = newNode;

which is not what you want.

Sign up to request clarification or add additional context in comments.

Comments

0
node ** head

Here head is a pointer to a pointer and (*head) is a pointer. So you need to access pointer like

(*head)->prev = newnode;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.