链接列表让我的大脑变得混乱。我应该怎么做?
我正在尝试使用链表作为一种方式来积累我对 C 中指针的知识。所以,我写了一个小例子,但是当我编译它时,我收到一个错误,我似乎无法弄清楚:
In function 'append_node':
error: request for member ‘next’ in something not a structure or union
什么是正确的通过引用访问(或传递)结构的方法?
#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, &curr);
head = curr;
}
curr = head;
while(curr) {
printf("%d\n", curr->val);
curr = curr->next ;
}
return 0;
}
任何帮助都会很棒!
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, &curr);
head = curr;
}
curr = head;
while(curr) {
printf("%d\n", curr->val);
curr = curr->next ;
}
return 0;
}
Any help would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可以假设您在这一行遇到错误吗?
我认为你需要做一个小小的改变:
由于
head
是一个指向指针的指针,当你取消引用它时,你会得到一个指针。->next
对该指针进行操作。Can I assume you're getting the error on this line?
I think you need to make one trivial change:
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 ofand change
to
请尝试以下操作:
将
**head
转换为*head
,然后在其上调用成员。Try this instead:
Turn
**head
to*head
and then call members on it.