![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3fa60b0324913772424728d88470156c.png#pic_center)
概念以及声明
概念:
结构是一些值的集合,这些值称为成员变量。结构的每个成员都是不同类型的变量
==注:==数组是一组相同类型的集合
声明
举一个学生的例子
推荐第一种
- 第一种
struct Student
{
char name[20];
char id[12];
char sex[3];
int high;
};
- 第二种
struct Student
{
char name[20];
char id[12];
char sex[3];
int high;
}x1,x2;
其中,x1,x2是根据Student结构体所创建的两个变量
这两个是全局结构体变量
创建:
结构体的成员可以是标量,数组,其他结构体
struct Student
{
char name[20];
char id[12];
char sex[3];
int high;
};
struct Pe
{
struct Student p1;
int num;
char ID_card[13];
};
变量的初始化:
- 单个结构体
#include <stdio.h>
struct Student
{
char name[20];
char id[12];
char sex[5];
int high;
};
int main()
{
struct Student p = { "张三","12312345678","男",183 };
return 0;
}
- 嵌套的结构体
#include <stdio.h>
struct Student
{
char name[20];
char id[12];
char sex[5];
int high;
};
struct Pe
{
struct Student p1;
int num[10];
};
int main()
{
struct Pe c = { {"张三","12312345678","男",183},123 };
return 0;
}
打印:
int main()
{
struct Student p = { "张三","12312345678","男",183 };
struct Pe c = { {"张三","12312345678","男",183},123 };
printf("%s %s %s %d\n", p.name, p.id, p.sex, p.high);
printf("%s %s %s %d %d\n", c.p1.name,c.p1.id,c.p1.sex,c.p1.high, c.num);
return 0;
}
结构体访问的方法
- 结构体指针
更好
struct Student
{
char name[20];
char id[12];
char sex[5];
int high;
};
void print2(struct Student* sp)
{
printf("%s %s %s %d\n", sp->name, sp->id, sp->sex, sp->high);
}
int main()
{
struct Student p = { "张三","12312345678","男",183 };
print2(&p);
return 0;
}
- 运算符
struct Student
{
char name[20];
char id[12];
char sex[5];
int high;
};
void print1(struct Student sp)
{
printf("%s %s %s %d\n", sp.name, sp.id, sp.sex, sp.high);
}
int main()
{
struct Student p = { "张三","12312345678","男",183 };
print1(p);
return 0;
}