2012-06-13 23 views
1

結構領域我的代碼:如何獲得用C

main() 
{ 
    typedef struct 
    { 
     int data; 
    } Information; 

    typedef Information *PtrInformation; 

    typedef struct InformationListStruct *PtrInformationListStruct; 

    typedef struct InformationListStruct 
    { 
     PtrInformationListStruct ptrNext; 
     PtrInformation ptrInf; 
    } PtrInformationListStructElement; 

    //============================== 

    PtrInformationListStruct list; 
    list = (PtrInformationListStruct)malloc(sizeof(InformationListStruct)); 
    PtrInformation ptr = (*list).ptrInf; // error !!! 

} 

編譯器拋出錯誤:

  • 「ptrInf」不是InformationListStruct的成員,因爲該類型尚未在函數main()

定義。如果我把這個行:

typedef struct InformationListStruct *PtrInformationListStruct; 

此線之後:將出現

typedef struct InformationListStruct 
    { 
     PtrInformationListStruct ptrNext; 
     PtrInformation ptrInf; 
    } PtrInformationListStructElement; 

然後其他錯誤:

  • 類型名稱中main()函數
  • 宣言丟失; ()

如何正確獲取「ptrInf」?

+3

只是一個小的話:把類型定義的函數體是不是一個很好的初步實踐給我。 – Synxis

+0

你有其他錯誤嗎?當您對錯誤有疑問時,最好將錯誤添加到問題中,並最好逐字(即複製粘貼)。 –

+0

我使用的是Unix GCC,我看到下面的錯誤: tc:函數'main': tc:22:51:錯誤:'InformationListStruct'未聲明(首次在此函數中使用) tc:22:51:注意:每個未聲明的標識符僅在其出現的每個函數中報告一次 – Viswesn

回答

5

You shouldn't cast malloc()'s return in C.此外,使用sizeof,不重複的類型名稱:

list = malloc(sizeof *list); 
+0

當然,這不可能是編譯錯誤的原因... –

+0

@LuchianGrigore它可以解決錯誤,你的解決方案也一樣通過添加缺少的'struct'關鍵字來使類型名稱合法。我的觀點是*有*類型名稱幾乎總是一個壞主意;只要在列表中定義了'list'就行了。 – unwind

+0

嗯現在我明白你的意思了:) –

3

你需要

list = (PtrInformationListStruct)malloc(sizeof(struct InformationListStruct)); 
//            | 
//           note struct keyword 

list = (PtrInformationListStruct)malloc(sizeof(PtrInformationListStructElement)); 

,因爲你有這方面的typedef

+1

OP似乎使用C而不是C++,所以'malloc'是創建新內存對象的好方法。 –

+1

他使用malloc,因爲代碼是C,而不是C++ – rkosegi

+0

@Luchian Grigore,請嘗試使用這兩個代碼片段。但仍然看到第一個錯誤。 –

1

在Visual Studio中,您正在使用哪種編譯器,您的代碼正在編譯成功。請避免函數體內的類型定義。

+0

我使用Borland編譯器(BCC55)。我必須嘗試視覺工作室 –

+0

這應該是一個評論。 Visual Studio編譯C++,如果你沒有命名文件'* .c',代碼是C. –

+1

嗯,我沒有數據太多的聲譽來添加評論,所以我發佈它作爲答案 – Tejendra