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?
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.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다