解決編譯錯誤:dereferencing pointer to incomplete type 的辦法

來源:互聯網
上載者:User

標籤:io   ar   使用   sp   strong   檔案   on   問題   cti   

在使用c語言寫程式時,可能遇到錯誤:error :dereferencing pointer to incomplete type。其實,這個錯誤是指標指向的結構體類型沒有定義。

原因可能有很多,但最多情況可能下面兩種:

1,使用庫函數或核心等提供的結構體時,沒有包含相應的標頭檔。解決方案很簡單,就是包含對應標頭檔就ok了。

2,若是自己定義的結構體,而且這個結構體恰恰是定義在.c檔案中。在這種情況下,在其他.c檔案中使用該結構體指標時,也會出現類似錯誤。

 

就第二種情況,筆者找到兩種解決方案:

1,將結構體定義放到.h檔案中,然後在使用該結構體的.c檔案中分別包含這個檔案。這種方法較符合常規。

在這裡需要注意,在定義標頭檔時,要使用先行編譯語句將標頭檔包圍起來。這樣做是防止出現標頭檔被重複包含的錯誤。

例如:

#ifndef  _ABC_H

#define _ABC_H

結構體定義

#endif

 

2,將結構體定義從上一個.c檔案中拷至出錯的.c檔案中,因為結構體定義只是聲明了結構體的大小並不真實分配空間,所以這樣做不會有問題。

範例程式碼:

a.c

#include <stdio.h>
struct obj_t { int x; int y; };
struct obj_t obj;
struct obj_t * get_obj() { obj.x = 11; obj.y = 22;
return &obj; }
void show(struct obj_t *p) { printf("a=%d\nb=%d\n", p->x, p->y, __func__); }

b.c

void call_show()

{ struct obj_t *p = get_obj();
p->x = 111; p->y = 222;
show(p); }

 

main.c

int main(int argc, char **argv) { call_show(); }

執行命令:gcc a.c b.c main.c -o test

出現如下錯誤:

b.c: In function ‘call_show’: b.c:10: warning: initialization makes pointer from integer without a cast b.c:12: error: dereferencing pointer to incomplete type b.c:13: error: dereferencing pointer to incomplete tyd;"

 

如下修改b.c後,錯誤消失

struct obj_t { int x; int y; };
void call_show() { struct obj_t *p = get_obj();
p->x = 111; p->y = 222;
show(p); }

解決編譯錯誤:dereferencing pointer to incomplete type 的辦法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.