I'm attempting to use linked lists as a way to buildup my knowledge of pointers in C. So, I wrote a small example but when I compile it I'm getting an error I can't seem to figure out:
In function 'append_node':
error: request for member ‘next’ in something not a structure or union
What's the proper way to access (or pass) a structure by reference?
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node *next;
};
static int append_node(int val, struct node **head) {
struct node *new_node;
new_node = (struct node *) malloc(sizeof(struct node));
new_node->val = val;
new_node->next = NULL
*(head)->next = new;
return 0;
}
int main() {
int i;
struct node *head;
struct node *curr;
head = NULL;
curr = (struct node *) malloc(sizeof(struct node));
for(i = 1; i <= 10; i++) {
append_node(i, &a开发者_Go百科mp;curr);
head = curr;
}
curr = head;
while(curr) {
printf("%d\n", curr->val);
curr = curr->next ;
}
return 0;
}
Any help would be great!
Can I assume you're getting the error on this line?
*(head)->next = new;
I think you need to make one trivial change:
(*head)->next = new;
Since head
is a pointer to a pointer, when you dereference it you get a pointer. The ->next
operates on that pointer.
Two problems:
There is a missing ;
at the end of
new->next = NULL
and change
*(head)->next = new;
to
(*head)->next = new;
Try this instead:
(*head)->next = new_node;
Turn **head
to *head
and then call members on it.
精彩评论