list.h
#ifndef LIST_H
#define LIST_H
/* Function prototypes */
struct nodeStruct* List_createNode(int item);
#endif
list.c
#include <stdio.h>
#include <stdlib.h>
struct nodeStruct {
int item;
struct nodeStruct *next;
};
struct nodeStruct* List_createNode(int item) {
struct nodeStruct *node = malloc(sizeof(struct nodeStruct));
if (node == NULL) {return NULL;}
node->item = item;
node->next = NULL;
return node;
}
Main.c:
#include "list.h"
#include <assert.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct nodeStruct *one = List_createNode(1);
while(one != NULL) {
printf("%d", one->item); //error
one= one->next; //error
}
错误:错误:取消引用指向不完整类型的指针 printf("%d", one->item);
错误出现在 one->item
处,我尝试了几种组合来取消引用,但似乎不起作用。正确的做法是什么?
更新:
list.h
#ifndef LIST_H
#define LIST_H
struct nodeStruct {
int item;
struct nodeStruct *next;
};
/* Function prototypes */
struct nodeStruct* List_createNode(int item);
#endif
现在的错误是,“sizeof”对不完整类型“struct nodeStruct”的无效应用
struct nodeStruct *node = malloc(sizeof(struct nodeStruct));
来 self 的 list.c 文件。
最佳答案
我可以想到几种方法:
将
struct
的定义放在头文件中,并将#include
头文件放在main.c
中。添加几个函数
int getNodeItem(struct nodeStruct* node) { return node->item; } struct nodeStruct* getNextNode(struct nodeStruct* node) { return node->next; }
并从
main
调用函数。while (one != NULL) { printf("%d", getNodeItem(one)); one = getNextNode(one); }
关于C:解引用指向不完整类型单链表的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143630/