一、定义
结构体是一些值的集合,这些值称为成员变量,结构的每个成员可以是不同类型的变量。
1.先定义结构体类型再定义变量名
格式:
struct 结构体名
{
数据类型 成员名1;
数据类型 成员名2;
:
数据类型 成员名n;
};
代码:
#include <stdio.h>
struct Student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
};
int main()
{
struct Student lisi = { "李四",28,"女" };
printf("name=%s\n", lisi.name);
return 0;
}
输出:
2.定义结构体类型别名
#include <stdio.h>
typedef struct Student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
}STU;
int main()
{
STU lisi = { "李四",28,"女" };
printf("name=%s\n", lisi.name);
return 0;
}
输出:
二、初始化和访问
1.初始化
格式:
struct 结构体名称 变量名称 ={};
代码:
#include <stdio.h>
struct student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
}STU;
int main()
{
// 初始化
struct student aa = { "qx",20,"男"};
return 0;
}
2.结构体成员的访问
结构变量的成员是通过点操作符(.)访问的。点操作符接受两个操作数。 例如:
#include <stdio.h>
struct student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
}STU;
int main()
{
// 初始化
struct student aa = { "qx",20,"男"};
printf("name=%s\n", aa.name);
printf("age=%d\n", aa.age);
printf("sex=%s\n", aa.sex);
return 0;
}
输出:
结构体指针访问指向变量的成员,有时候我们得到的不是一个结构体变量而是一个结构体的指针,我们可以使用以下的方式进行成员的访问。
#include <stdio.h>
struct student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
}STU;
int main()
{
// 初始化
struct student aa = { "qx",20,"男"};
// 结构体指针变量
struct student *temp = &aa;
// 结构体指针访问成员
printf("name=%s\n", temp->name);
printf("age=%d\n", temp->age);
printf("sex=%s\n",temp->sex);
printf("--------------\n");
printf("name=%s\n", (*temp).name);
printf("age=%d\n", (*temp).age);
printf("sex=%s\n", (*temp).sex);
return 0;
}
输出:
三、结构体传参
结构体参数可以分为结构体参数和结构体地址参数。
#include <stdio.h>
struct Student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
};
//结构体传参
void print1(struct Student s)
{
printf("name=%s\n", s.name);
}
//结构体地址传参
void print2(struct Student* s)
{
printf("name=%s\n", s->name);
}
int main()
{
struct Student zhangsan = { "张三",25,"男" };
print1(zhangsan);
print2(&zhangsan);
return 0;
}
输出:
虽然两种方式都可以获取到结构体的数据,但是我们推荐使用结构体地址参数的函数。因为如果传递一个结构体对象的时候,如果结构体过大,参数压栈的系统开销较大,所以会导致性能的下降。
四、结构体数组
结构体数组里面的元素是结构体对象。
#include <stdio.h>
struct Student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
};
void show(struct Student *stu)
{
printf("name=%s\n", stu->name);
printf("age=%d\n", stu->age);
printf("sex=%s\n", stu->sex);
printf("--------------\n");
}
int main()
{
struct Student lisi = { "李四",28,"女" };
struct Student zhangsan = { "张三",25,"男" };
struct Student arr[2] = { zhangsan,lisi };
show(&arr[0]);
show(&arr[1]);
return 0;
}
输出:
五、结构体指针数组
#include <stdio.h>
struct Student
{
char name[50]; //姓名
int age; //年龄
char sex[5];//性别
};
void show(struct Student *stu)
{
printf("name=%s\n", stu->name);
printf("age=%d\n", stu->age);
printf("sex=%s\n", stu->sex);
printf("--------------\n");
}
int main()
{
struct Student lisi = { "李四",28,"女" };
struct Student zhangsan = { "张三",25,"男" };
// 结构体指针数组 里面的元素是结构体的地址
struct Student *arr[2] = { &zhangsan,&lisi };
// 直接取出地址访问
show(arr[0]);
show(arr[1]);
return 0;
}
输出: