【问题标题】:C: dereferencing pointer to incomplete type singly linked listC:取消引用指向不完整类型单链表的指针
【发布时间】:2015-01-26 01:29:42
【问题描述】:

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
}

错误:error: dereferencing pointer to incomplete type printf("%d", one->item); 错误在one-&gt;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

现在的错误是,invalid application of ‘sizeof’ to incomplete type ‘struct nodeStruct’ struct nodeStruct *node = malloc(sizeof(struct nodeStruct)); 来自我的 list.c 文件。

【问题讨论】:

  • 您是否在主 .c 文件中包含了 struct nodeStruct 的定义?此外,您可能希望删除 one = *one-&gt;next; 中的 *。哦,修改one 可能会泄漏内存。
  • @EOF 这不是问题,因为其他方法也有效。
  • 所以struct nodeStruct 的定义实际上main() 不可用。将struct nodeStruct定义放入list.h。提示:目前在list.c
  • ...现在你还需要#include "list.h" in list.c
  • 实际上,您的int main() 函数在哪里?它不在您发布的main.c

标签: c pointers gcc linked-list


【解决方案1】:

我可以想到几种方法:

  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);
    }
    

【讨论】:

  • #1 不起作用。然而,#2 做到了。为什么我不能直接使用 printf?
  • @Aaron:你使用的是 C++ 编译器吗?
  • @Aaron,#1 没有理由不起作用。如果您可以使用其他信息和更新的代码更新您的帖子,我们可以解决这个问题。
  • @EOF 从 ubuntu 运行 gdb
  • @Aaron: gdb 是一个调试器。我猜你的意思是gcc
【解决方案2】:

list.c 中添加#include "list.h"。当gcc 尝试编译后者时,编译器的本地调用不知道struct nodeStruct,因为它的定义尚未包含在本地文件中。

注意:这是基于您的更新,其中struct nodeStructlist.h 中定义。

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    相关资源
    最近更新 更多