结构体变量
初始化结构体变量
1.结构一定有struct
第种:struct 结构体名
{
成员列表
}变量名列表;
第二种:
struct
{
成员列表
}变量名列表;
所以struct data
{
int a;
char b;
float c;
}data1;
去掉data后,就省略了结构体名,直接定义结构体变量(data1);但也不能定义其他同结构体变量了
结构体类型定义并不分配内存,但结构体变量一定会分配内存
2.结构体变量的作用:方便人们将不同的数据类型建立联系输出
#include <stdio.h>
struct student
{
int num;
char name[20];
char sex;
float score;
}stu1;
struct student stu1={10,"li ling",'m',80};
main()
{
printf("%d %s",stu1.num,stu1.name);
}
如果需要,可以在后面定义更多的结构体变量
struct student stu1,stu2,stu3;
- 结构体变量及其成员的引用: 结构体变量名.结构体成员名
- 初始化:
struct student stu1={10,"li ling",'m',80};
- 上述所学代码展示
#include <stdio.h>
void main()
{
struct student //定义一个结构体变量
{
int num;
char name[20];
char sex;
float score;
}stu1={1,"li ying",'m',89}; //赋值的一种方法
struct student stu2;
scanf("%d%s%c%d",&stu2.num,stu2.name,&stu2.sex,&stu2.score);//赋值的第二种方法
printf("the most high score");
if(stu1.score>stu2.score)
printf("%d %s %c %d",stu1.num,stu1.name,stu1.sex,stu1.score);
else
printf("%d %s %c %d",stu2.num,stu2.name,stu2.sex,stu2.score); //输出的格式
}
结构体嵌套
结构体中还有一个结构体
取结构体里面的值(类似赋值,引用)最外层结构体变量名.内层结构体变量名.结构体成员名
#include <stdio.h>
void main()
{
struct Birthdate
{
int year;
int month;
int day;
};
struct student
{
int num;
int age;
struct Birthdate birth;
float score;
char name[20];
}stu1={1,18,{2001,01,05},99,"li ying"};
printf("%d %d %d %d %d %f %s",stu1.num,stu1.age,stu1.birth.year,stu1.birth.month,stu1.birth.day,stu1.score,stu1.name);
}
来源:CSDN
作者:qq_1927555795
链接:https://blog.csdn.net/qq_45720531/article/details/103733888