[英]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 中,我嘗試初始化結構列表的兩個指針(第一個和最后一個):
#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;
};
帶有 function 主文件的文件僅包含module.h
模塊.h 具有這些不完整類型的聲明
typedef struct date date;
typedef struct list list;
所以編譯器發出錯誤,因為當它編譯翻譯單元時,它不知道聲明的類型是否有數據成員first
和last
。
您應該將完整的結構聲明放在 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 動態分配 memory 也沒有什么意義
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
。 這個方法對我有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.