[英]Struct in a struct using typedef - C
如何在C
使用typedef
在另一个struct
正确使用一个struct
?
这种方法不起作用,我不明白为什么:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char *nume;
char *prenume;
data data;
} student;
typedef struct
{
int an,zi,luna;
} data;
int main()
{
student Andrei;
scanf("%s %s %d ",Andrei.nume,Andrei.prenume,&Andrei.b.an);
printf("%s %s %d ",Andrei.nume,Andrei.prenume,Andrei.data.an);
return 0;
}
您的代码中实际上存在许多错误!
首先,您需要先声明/定义任何struct
对象,然后再将其用作另一个struct
的成员。
其次,您的nume
和prenume
成员被声明为指向字符的指针,但它们没有初始化为任何内容,也没有为这些字符串分配任何内存。
第三,您的scanf
行中有一个“错字”:大概Andrei.b.an
应该是Andrei.data.an
。
最后(我认为),因为scanf
的格式字符串中有一个尾随空格,该函数至少需要一个“额外”输入字段才能完成。
这是一个潜在的“修复”,在我进行更改的地方添加了评论:
#include <stdio.h>
// <stdlib.h> // You don't use this - perhaps thinking of using "malloc" for "nume" and "prenume"??
typedef struct // This MUST be defined BEFORE it is used as a member in the following struct!
{
int an, zi, luna;
}data;
typedef struct
{
char nume[32]; // Here, we create fixed char arrays (strings) for "nume"...
char prenume[32]; // ... and "prenume". You can change the sizes, as you need!
data data;
} student;
int main()
{
student Andrei;
scanf("%s %s %d", Andrei.nume, Andrei.prenume, &Andrei.data.an); // Note: removed trailing space from format!
printf("%s %s %d", Andrei.nume, Andrei.prenume, Andrei.data.an);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.