C:解引用指向不完整类型单链表的指针

标签 c pointers gcc linked-list

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 文件。

最佳答案

我可以想到几种方法:

  1. struct的定义放在头文件中,并将#include头文件放在main.c中。

  2. 添加几个函数

    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/

相关文章:

c - 套接字服务器内存使用率上升,变得无响应

c - 这段代码是关于什么的?

c - 如何避免在信号处理程序中使用 printf?

c - 接受超过 FD_SETSIZE 的连接

c - 如何计算两个地址之间的距离?

c++ - QPointer::clear() 是否删除其引用的指针,或者 "Clears this QPointer object."是否有其他含义?

Javascript:将两个对象合并为一个

c - 关于 Makefile 中的 CFLAGS

c - 使用 -g、-ggdb、-g3 或 -ggdb3 时,GCC 不会生成调试器信息

c++ - CMake add_compile_options 在适当的时候会影响链接器选项吗?