2010-04-05 38 views
33

我有一個結構定義爲:C編程:取消引用指針不完全型誤差

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; 
... 

我收到以下錯誤:

error: dereferencing pointer to incomplete type

無論何時我嘗試訪問newFile中的成員。我究竟做錯了什麼?

+0

謝謝大家的幫助:) – confusedKid 2010-04-05 01:59:50

+0

順便說一句,我有同樣的錯誤,但問題是我沒有包括一個特定的頭文件(在一個大項目中)。 – ady 2016-05-06 18:51:39

回答

41

您尚未在第一次定義中定義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名字被放置在定義你應該做的。

+1

+1比我更快,並且使用'struct stasher_file'而不是'typedef'與在示例中OP使用類型一致。如果已經將結構定義爲typedef struct {...} stasher_file,則爲 – Dirk 2010-04-05 01:52:53

13

您正在使用指針newFile而不爲其分配空間。

struct stasher_file *newFile = malloc(sizeof(stasher_file)); 

此外,你應該把結構名稱放在頂部。您指定stasher_file的位置是創建該結構的實例。

struct stasher_file { 
    char name[32]; 
    int size; 
    int start; 
    int popularity; 
}; 
+0

如何爲它分配空間? – confusedKid 2010-04-05 01:47:49

+0

我沒有爲newFile分配空間,但將stasher_file的定義更改爲像您的那樣,並且錯誤未出現。我還需要分配空間嗎? – confusedKid 2010-04-05 01:55:26

+1

@confuseKid:是的,你需要像我給的那樣分配空間。也請務必在完成時釋放它。 – 2010-04-05 01:57:09

10

您是如何真正定義結構的?如果

struct { 
    char name[32]; 
    int size; 
    int start; 
    int popularity; 
} stasher_file; 

是被視爲類型定義,它缺少一個typedef。如上所述,您實際上定義了一個名爲stasher_file的變量,其類型是某種匿名結構類型。

嘗試

typedef struct { ... } stasher_file; 

(或者,如已被別人提及):

struct stasher_file { ... }; 

後者實際上你的類型搭配使用。第一種形式將要求您在變量聲明之前刪除struct

1

爲什麼你得到這個錯誤的原因是因爲你已經宣佈你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; 
}; 

但要注意,雖然布萊恩R.邦迪的反應是不是你的錯誤信息是正確的,他是對的,你嘗試寫入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-終止。)

+0

;那麼你可以使用malloc作爲stasher_file * newFile = malloc(sizeof(stasher_file); – katta 2013-04-22 20:10:25

+0

@katta是的,但很多人認爲這是一個更好的做法,而不是'T * p = malloc(sizeof * p)'。如果'p'的類型改變了,你只需要更新它的聲明,而不是'malloc'站點。忘記更新'malloc'站點會默默地分配錯誤的內存量,可能導致緩衝區溢出 – jamesdlin 2013-04-22 23:06:59

+0

@ katta另見http://stackoverflow.com/questions/373252/c-sizeof-with-a-type-or-variable – jamesdlin 2013-04-22 23:34:30

5

上面的情況是針對一個新項目。編輯已建立好的庫的分支時,我遇到了這個錯誤。

typedef包含在我正在編輯的文件中,但結構不是。

最終的結果是我試圖在錯誤的地方編輯結構。

如果你以類似的方式運行它,請查找結構被編輯的其他地方並在那裏嘗試。

+1

+1,因爲這句話讓我走上正軌! – Ludo 2013-10-10 11:09:31

相關問題