嵌入式学习笔记19.11.25
c语言结构体
结构体一般定义全局变量
struct stu{//struct 定义结构体 stu 结构体名称
int num;
char name;
int score[3];
}student[5];//student 结构体数组名
#include <stdio.h>
//结构体
struct stu{
int num;//学号
char name[10];//姓名
char s;//性别
int classname;//班级
int score[3];//成绩
}student[10] = {{1,"zhang",'m',1,95,96,97},{2,"wang",'w',1,94,95,98},{3,"li",'w',1,80,97,100}};
int main(){
int i;
for(i = 0;i < 3;i++){
printf("%d %s %c %d %d %d %d\n",student[i].num,student[i].name,student[i].s, \
student[i].classname,student[i].score[0],student[i].score[1],student[i].score[2]);
}
for(i = 3;i < 4;i++){
//一个汉字在字符串里占两个大小
scanf("%d",&student[i].num);
scanf("%s",student[i].name);
fflush(stdin);//清除缓存,终止字符串录入
scanf("%c",&student[i].s);
scanf("%d",&student[i].classname);
scanf("%d",&student[i].score[0]);
scanf("%d",&student[i].score[1]);
scanf("%d",&student[i].score[2]);
}
for(i = 0;i < 4;i++){
printf("%d %s %c %d %d %d %d\n",student[i].num,student[i].name,student[i].s, \
student[i].classname,student[i].score[0],student[i].score[1],student[i].score[2]);
}
}
结构体可以嵌套:
#include <stdio.h>
struct stu1{
char nun;
int sun;
}student1[3]={
{'a',2},{'b',4},{'c',6}
};
struct stu{
struct stu1 student2;
char sum;
}student[5] ={
{'z',3,'y'},{'r',5,'e'}
};
int main(){
int i;
for(i = 0;i < 2;i++){
printf("%c %d %c\n",student[i].student2.nun,student[i].student2.sun,student[i].sum);
}
}