C - 打印链表的头部

C - Printing the head of a linked list

我正在尝试从一串由空格分隔的整数构建一个链表。字符串中的每个整数都会被添加到链表中,除了-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 成员的双指针的取消引用,因此首先它尝试从不存在的双指针中获取 int 成员。 所以这就是为什么你需要加上括号,所以它会将 head_ptr 评估为双指针的取消引用,并将使用该结构的 int 成员。