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

时间:2015-01-26 01:29:42

标签: 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
}

错误:error: dereferencing pointer to incomplete type 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

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

2 个答案:

答案 0 :(得分:2)

我可以想到几种方式:

  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 :(得分:0)

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

注意:这取决于您在struct nodeStruct中定义list.h的更新。