如何在结构中初始化指针但结构在模块中

How to initialize pointers within a struct but the struct is in a module

也许这是一个愚蠢的问题,但我找不到解决方案。我找到的大多数答案都适用于主文件中的结构。我想在模块中定义结构 (list),因为此模块中的某些函数与结构一起使用。稍后结构应该成为列表的根。

我的module.c是:

#include"modul.h"

struct date{
    int date_date;
};

struct list{
    date *first;
    date *last;
};

我的module.h是:

typedef struct date date;
typedef struct list list;

在main.c中,我尝试初始化结构[=30]的两个指针(firstlast) =]列表:

#include<stdio.h>
#include<stdlib.h>
#include"module.h"

int main(){
    
    list *mylist=malloc(sizeof(mylist));
    
    mylist->first=NULL;
    mylist->last=NULL;
    
    printf("test");
    
    return 0;
}

我尝试用gcc编译:

gcc -Wall -std=c99 main.c module.c -o main

并得到以下错误:

main.c: In function 'main':
main.c:9:11: error: dereferencing pointer to incomplete type 'list {aka struct list}'
     mylist->first=NULL;
           ^~

我做错了什么?我希望我使代码尽可能简单。使用 mylist.first=NULL; 我也得到一个错误。

您应该在 .h 文件中定义结构。 另外,最好像这样定义一个结构:

typedef struct date {
    int date_date;
}DATE;

typedef struct list {
    DATE *first, *last;
}LIST;

那么在你的主菜单上你可以有:

int main (){
    LIST *mylist = malloc(sizeof(struct list));
    mylist -> first = NULL;
    mylist -> last = NULL;
return 0;
}

此外,不要忘记包含 stdio.h 以便使用 NULL。 这个方法对我有用

对于初学者这些声明

struct date{
    int date_date;
};

struct list{
    date *first;
    date *last;
};

错了,没有意义。

例如此声明

struct list{
    date *first;
    date *last;
};

编译器会报错,类型名date没有声明。您声明了类型 struct date 而不是 date.

但即使你会写对

struct list{
    struct date *first;
    struct date *last;
};

您不会构建列表,因为结构 date 没有指向类型 struct date.

的下一个或前一个 object 的指针

您可以像这样声明结构(对于 singly-linked 列表)

struct date{
    int date_date;
    struct date *next;
};

struct list{
    struct date *first;
    struct date *last;
};

或喜欢(对于 doubly-linked 列表)

struct date{
    int date_date;
    struct date *next;
    struct date *prev;
};

struct list{
    struct date *first;
    struct date *last;
};

具有函数 main 的文件仅包含具有这些不完整类型声明的 header module.h

typedef struct date date;
typedef struct list list;

所以编译器会报错,因为当它编译翻译单元时,它不知道声明的类型是否有数据成员 firstlast.

您应该将完整的结构声明放在 header.

例如

struct date{
    int date_date;
    struct date *next;
};

struct list{
    struct date *first;
    struct date *last;
};

typedef struct date date;
typedef struct list list;

此外,为 object 类型的结构列表动态分配内存也没有什么意义,例如

list *mylist=malloc(sizeof(mylist));

而且那是不正确的。

你可以直接写

list mylist = { .first = NULL, .last = NULL };