如何在C中获取struct字段

hel*_*igo 1 c struct

我有代码:

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 !!!

}
Run Code Online (Sandbox Code Playgroud)

编译器抛出错误:

  • "ptrInf"不是InformationListStruct的成员,因为函数main()中尚未定义类型

如果我把这一行:

typedef struct InformationListStruct *PtrInformationListStruct;
Run Code Online (Sandbox Code Playgroud)

在这之后:

   typedef struct InformationListStruct
   {
      PtrInformationListStruct ptrNext;
      PtrInformation ptrInf;
   } PtrInformationListStructElement;
Run Code Online (Sandbox Code Playgroud)

然后出现其他错误:

  • 函数main()中预期的类型名称
  • 宣言缺失; 在函数main()中

如何正确获得"ptrInf"?

unw*_*ind 5

你不应该malloc()在C中强制转换.另外,使用sizeof,不要重复类型名称:

list = malloc(sizeof *list);
Run Code Online (Sandbox Code Playgroud)