如何解决C-打印链接列表的标题
我正在尝试从由空格分隔的整数字符串构建链表。字符串中的每个整数都将添加到链接列表中,-1除外。但是,当我尝试在列表的头节点中打印数据时,出现错误Member reference base type 'Node *' (aka 'struct node *') is not a structure or union
。为什么我不能在该行中打印head_ptr
的数据?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node Node;
struct node {
int data;
Node *next;
};
void build_linked_list(Node **head_ptr) {
char *string = malloc(1028);
char *p = string,*found = string;
Node *nextNode = NULL;
if (fgets(string,1028,stdin) != NULL) {
while ((found = strsep(&p," \n")) != NULL) {
if (strcmp(found,"-1") == 1) {
Node node = {atoi(found),nextNode};
nextNode = &node;
}
}
}
*head_ptr = nextNode;
printf("%i\n",*head_ptr->data); // can't print data in head node
free(string);
}
int main() {
Node *head = NULL;
build_linked_list(&head);
return EXIT_SUCCESS;
}
解决方法
您需要在head_ptr周围加上括号才能使其正常工作,例如:(*head_ptr)->data)
由于编译器将表达式评估为具有int成员的双指针的解引用,因此出现了问题,因此首先尝试从不存在的double指针获取int成员。
因此,这就是为什么需要放置括号的原因,因此它将head_ptr评估为对双指针的取消引用,并将使用该结构的int成员。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。