[英]C how to access a struct member in a struct?
I have a struct that has a struct as a member, and I want to access that member from the first struct. 我有一个具有作为成员的结构的结构,我想从第一个结构访问该成员。 You didn't get it? 你不明白吗? I will show you. 我给你看。
typedef struct
{
int day;
} Date;
typedef struct
{
struct Date;
} Insert;
Insert insert;
scanf("%d", &insert.day); // I tried this but it doesn't work
scanf("%d", &insert.date.day); // Figured maybe this would do it, but nope
You need : 你需要 :
typedef struct
{
Date date;
} Insert;
Insert insert;
Then, 然后,
scanf("%d", &insert.date.day);
As others have said , the way you have your code written, it will not build. 正如其他人所说的那样,您编写代码的方式将无法构建。 You should get an error where indicated in the following: 您应该在以下指示的地方得到一个错误:
typedef struct
{
int day;
} Date;
typedef struct
{
struct Date;//Error here - Undefined size for field, incomplete struct Date defined at cfile.c:8
} Insert;
Insert insert;
int main(void)
{
return 0;
}
You have already created a type Date
(ie typedef struct
... Date
), use it instead of struct Date;
您已经创建了Date
类型(即typedef struct
... Date
),使用它代替struct Date;
like this: (this will build) 像这样:( 这将建立)
#include <ansi_c.h>
typedef struct
{
int day;
} Date;//you have just created a new type: struct Date here..., use "Date date;" below, (not struct Date;)
typedef struct
{
Date date;//"Date is a type (typedef struct Date), so use it here to declare the member "date"
} Insert;
Insert insert;
int main(void)
{
return 0;
}
int main(void)
{
scanf("%d", &insert.date.day);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.