简体   繁体   English

如何在C中获取结构字段

[英]How to get struct field in C

I have the code: 我有代码:

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

}

The compiler throw the error: 编译器抛出错误:

  • "ptrInf" is not a member of InformationListStruct, because the type is not yet defined in function main() “ ptrInf”不是InformationListStruct的成员,因为该类型尚未在函数main()中定义

If I put this line: 如果我把这一行:

typedef struct InformationListStruct *PtrInformationListStruct;

after this lines: 在这行之后:

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

then other error appears: 然后出现其他错误:

  • Type name expected in function main() 函数main()中预期的类型名称
  • Declaration missing ; 宣言遗失; in function main() 在函数main()中

How to get "ptrInf" correctly? 如何正确获取“ ptrInf”?

您不应该在C中malloc()的返回值。此外,请使用sizeof ,不要重复类型名称:

list = malloc(sizeof *list);

You need 你需要

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

or 要么

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

since you have a typedef for it. 因为您有一个typedef

Which Compiler are you using, in visual studio , your code is compiling successfully. 您正在Visual Studio中使用哪个编译器,代码已成功编译。 Please avoid type definations inside the body of a function. 请避免在函数体内进行类型定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM