基本结构
注意最后那个大括号后面有分号
#include<stdio.h>
struct student
{
int id;
char name;
struct teacher
{
int age;
}th;
};
int main()
{
int id=10;
struct student stu;
stu.id=6666;
stu.name='d';
stu.th.age=18;
printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stu.id,stu.name,stu.th.age);
return 0;
}
结构体中也可以有结构体
#include<stdio.h>
struct student
{
int id;
char name;
struct teacher
{
int age;
}th;
}stu;
int main()
{
int id=10;
stu.id=6666;
stu.name='d';
stu.th.age=18;
printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stu.id,stu.name,stu.th.age);
return 0;
}
可以直接在花括号后面直接赋值给结构体一个变量
#include<stdio.h>
struct student
{
int id;
char name;
struct teacher
{
int age;
}th;
};
int main()
{
int id=10;
struct student stu={6666,'d',18};
printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stu.id,stu.name,stu.th.age);
return 0;
}
也可以用大括号按顺序给结构体中的成员赋值
typedef
#include<stdio.h>
typedef struct student
{
int id;
char name;
struct teacher
{
int age;
}th;
}stu;
int main()
{
int id=10;
stu stt;
stt.id=6666;
stt.name='d';
stt.th.age=18;
printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stt.id,stt.name,stt.th.age);
return 0;
}
使用typedef可以直接用花括号后面的stu表示一长串的struct student,后面给结构体赋值变量时可简洁一点
结构体数组
结构体数组就是数组里面存放的是结构体
#include<stdio.h>
struct student
{
int id;
char name;
}stu[10];
int main()
{
stu[0].id=20;
stu[0].name='d';
stu[1].id=11;
stu[1].name='p';
printf("stu[0].id=%d\nstu[0].name=%d\nstu[1].id=%d\nstu[1].name=%d\n",stu[0].id,stu[0].name,stu[1].id,stu[1].name);
return 0;
}