[英]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 成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.