[英]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: 编译器抛出错误:
If I put this line: 如果我把这一行:
typedef struct InformationListStruct *PtrInformationListStruct;
after this lines: 在这行之后:
typedef struct InformationListStruct
{
PtrInformationListStruct ptrNext;
PtrInformation ptrInf;
} PtrInformationListStructElement;
then other error appears: 然后出现其他错误:
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.