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

问题描述

也许这是一个愚蠢的问题,但我找不到解决方案。我发现的大多数答案适用于主文件中的结构。我想在模块中定义结构(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 中,我尝试初始化结构体 list 的两个指针(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; 我也得到一个错误。

解决方法

对于初学者来说,这些声明

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 类型对象的指针。

你可以像这样声明结构(对于单链表)

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

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

或喜欢(用于双向链表)

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

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

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

typedef struct date date;
typedef struct list list;

因此编译器会发出错误,因为在编译翻译单元时,它不知道声明的类型是否具有数据成员 firstlast

您应该将完整的结构声明放在标题中。

例如

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

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

typedef struct date date;
typedef struct list list;

此外,为结构列表类型的对象动态分配内存也没有太大意义

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

而且这是不正确的。

你可以直接写

list mylist = { .first = NULL,.last = 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。 这个方法对我有用

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...