C语言 在链表中打印 head 指向的项目时出现取消引用错误



我正在尝试打印头部指向的节点项目,但我最终得到一个"取消引用指向不完整类型"结构节点结构"错误的指针。 未显示的代码包括 list.h 文件和类的其他函数。

相关代码: 列表.c:

struct nodeStruct {
int item;
struct nodeStruct *next;
};
/*
* Allocate memory for a node of type struct nodeStruct and initialize
* it with the value item. Return a pointer to the new node.
*/
struct nodeStruct* List_createNode(int item) {
struct nodeStruct *newNode = malloc(sizeof(struct nodeStruct));
newNode->item = item;
newNode->next = NULL;
printf("New node created with item %dn", newNode->item);
return newNode;
}

/*
* Insert node at the head of the list.
*/
void List_insertHead (struct nodeStruct **headRef, struct nodeStruct *node) {
if(*headRef == NULL) {
printf("List is empty, creating new headn");
*headRef = node;
printf("Empty list new head: %dn", (*headRef)->item);
}
// Head already exists, shift pointer of head to new node
// and change new head pointer to old head
else {
struct nodeStruct* oldHead = *headRef;
printf("Old head item: %dn", oldHead->item);
node->next = *headRef;
*headRef = node;
printf("New Head: %d // Old head: %dn", (*headRef)->item, node->next->item);
}
}

test_list.c:

int main(int argc, char** argv)
{
printf("Starting tests...n");
struct nodeStruct* head = NULL;
// Create 1 node:
struct nodeStruct* firstNode = List_createNode(0);
List_insertHead(&head, firstNode);
printf("%dn", head->item); // error

制作文件:

CC=cc
CXX=CC
CCFLAGS= -g -w -std=c99 -Wall -Werror

all: test_list test
# Compile all .c files into .o files
# % matches all (like * in a command)
# $< is the source file (.c file)
%.o : %.c
$(CC) -c $(CCFLAGS) $<

test_list: list.o test_list.o
$(CC) -o test_list list.o test_list.o
test: test_list
./test_list

clean:
rm -f core *.o test_list

打印磁头>项目的目的是查看磁头是否正常工作。

您缺少头文件。

C 将每个源文件分别编译为目标文件。然后它将它们链接在一起。每个 .c 文件都必须知道它使用的所有类型和函数的签名。这意味着test_list.c必须知道list.c中结构和函数的签名。目前没有。

您可以使用#include list.c直接在test_list.c中包含list.c,这基本上list.c粘贴到test_list.c中。这将起作用,但是list.c不能被任何其他文件使用而不会引起各种问题。

更好的方法是创建一个头文件,它声明所有类型并转发声明所有函数。前向声明让编译器知道哪些函数可用以及它们的签名是什么,并承诺稍后会定义其他函数。

// list.h
struct nodeStruct {
int item;
struct nodeStruct *next;
};
struct nodeStruct* List_createNode(int);
void List_insertHead (struct nodeStruct **, struct nodeStruct *);

现在,test_list.clist.c都可以#include "list.h"为编译器提供足够的信息,以便将每个源文件编译为目标文件。然后这些对象将被链接在一起,并告诉test_list.o在list.o中的位置可以找到函数。

# Compile list.c into list.o using the declarations in list.h
cc -c -g -w -std=c99 -Wall -Werror list.c
# Compile test_list.c into test_list.o using the declarations in list.h
cc -c -g -w -std=c99 -Wall -Werror test_list.c
# Link both object files into an executable so test_list.o can
# use the functions compiled into list.o
cc -o test_list list.o test_list.o

您的代码工作正常:

查看结果:

Starting tests...
New node created with item 0
List is empty, creating new head
Empty list new head: 0
0

也许是您的编译过程有关。

最新更新