![](/img/trans.png)
[英]compiler error - dereferencing pointer to incomplete type In C programming
[英]C programming: Dereferencing pointer to incomplete type error
我有一個結構定義為:
struct {
char name[32];
int size;
int start;
int popularity;
} stasher_file;
以及指向這些結構的指針數組:
struct stasher_file *files[TOTAL_STORAGE_SIZE];
在我的代碼中,我創建了一個指向結構的指針並設置其成員,並將其添加到數組中:
...
struct stasher_file *newFile;
strncpy(newFile->name, name, 32);
newFile->size = size;
newFile->start = first_free;
newFile->popularity = 0;
files[num_files] = newFile;
...
我收到以下錯誤:
錯誤:取消引用指向不完整類型的指針
每當我嘗試訪問newFile
的成員時。 我究竟做錯了什么?
您還沒有通過第一個定義定義struct stasher_file
。 您定義的是無名結構類型和該類型的變量stasher_file
。 由於代碼中沒有struct stasher_file
這樣的類型的定義,編譯器會抱怨類型不完整。
為了定義struct stasher_file
,您應該按如下方式完成
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
注意stasher_file
名稱放在定義中的位置。
您正在使用指針newFile
而不為其分配空間。
struct stasher_file *newFile = malloc(sizeof(stasher_file));
您還應該將結構名稱放在頂部。 您指定stasher_file的位置是創建該結構的實例。
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
你是如何實際定義結構的? 如果
struct {
char name[32];
int size;
int start;
int popularity;
} stasher_file;
將被視為類型定義,它缺少typedef
。 如上所述,您實際上定義了一個名為stasher_file
的變量,其類型是一些匿名結構類型。
嘗試
typedef struct { ... } stasher_file;
(或者,正如其他人已經提到的):
struct stasher_file { ... };
后者實際上匹配您對該類型的使用。 第一種形式要求您在變量聲明之前刪除struct
。
上面的案例是針對一個新項目。 我在編輯一個完善的庫的fork時遇到了這個錯誤。
typedef包含在我正在編輯的文件中,但結構卻沒有。
最終的結果是我試圖在錯誤的地方編輯結構。
如果您以類似的方式遇到此問題,請查找編輯結構的其他位置並在那里進行嘗試。
您收到該錯誤的原因是您已將struct
聲明為:
struct {
char name[32];
int size;
int start;
int popularity;
} stasher_file;
這不是聲明stasher_file
類型。 這是聲明一個匿名 struct
類型,並且正在創建一個名為stasher_file
的全局實例。
你的意圖是:
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
但請注意,雖然Brian R. Bondy對您的錯誤消息的回答不正確,但他是正確的,您正試圖在沒有為其分配空間的情況下寫入struct
。 如果你想要一個指向struct stasher_file
結構的指針數組,你需要調用malloc
來為每個結構分配空間:
struct stasher_file *newFile = malloc(sizeof *newFile);
if (newFile == NULL) {
/* Failure handling goes here. */
}
strncpy(newFile->name, name, 32);
newFile->size = size;
...
(順便說一句,使用strncpy
時要小心;不能保證NUL終止。)
原因是您沒有聲明類型struct stasher_file
,而是定義了一個 struct 變量stasher_file
。
在C
,結構的聲明:
struct structure-tag {
member1
member2
...
};
structure-tag
是跟在關鍵字struct
之后的可選名稱。 聲明后,您可以定義一個變量:
struct structure-tag var1, *var2;
此外,您可以同時進行聲明和定義,例如:
struct structure-tag {
member1
member2
...
} var1, *var2;
所以在你的情況下,你可以試試這個:
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
} *files[TOTAL_STORAGE_SIZE];
struct stasher_file *newFile = malloc(sizeof(struct stasher_file));
... other code ...
就這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.