C语言中的结构体数组
C语言中的结构体数组
1.结构体 数组概念 2. 结构体数组定义和初始化 3. 结构体数组的引用
结构体数组的概念
元素为结构体类型的数组称为结构体数组,在实际的应用过程中,经常使用结构体数组来表示具有相同数据结构的一个群体
struct student{ int xh; char *name; char *sex; }stu[20]; 定义了一个结构体数组stu,共有30个元素,stu[0]--stu[29]; 每个数组的元素都是struct student类型
结构体数组定义和初始化
1:先声明结构体,再去定义结构体数组
struct 结构体名{ 成员列表; }; struct 结构体名 数组名[长度] = { {成员值列表},...{成员值列表}}; struct 结构体名 数组名[长度] = {结构体变量1,...,结构体变量n};
2:声明结构体的同时去定义结构体数组(结构体名可以省略);
struct [结构体名] { 成员列表; }数组名[长度] ={ {成员值列表}...{成员值列表}};
结构体数组的引用
结构体数组名[下标].成员名 通过下表可以获得结构体数组中指定的结构体变量,然后再通过点运算符,可以获得结构体变量中的成员 如: struct student{ int xh; char name[]; }stu[4]; strcpy(stu[0].name,"Tom"); stu[1].xh = 1;
下面是对应的结构体数组的实际操作代码:
#include<stdio.h> #include<stdlib.h> //结构体中声明中尽量使用字符指针进行字符串操作,在初始化的时候会方便 //如果使用的是字符数组,那么会就要使用strcpy进行拷贝初始化 struct address{ char *country; char *city; }; struct teacher{ char *name; int age; struct address addr; }; void out_teacher(struct teacher tea); void out_all_teachers(struct teacher [],int num); int main(int argc,char *argv[]){ //先定义结构体变量,再进行定义结构体数组 struct teacher teacher_one = { "zhangsan",20,{ "china","shanghai"}}; struct teacher teacher_two = { "lisi",25,{ "china","hefei"}}; struct teacher teachers_one [] = {teacher_one,teacher_two}; out_all_teachers(teachers_one,2); printf("----------------------------- "); //在定义结构体数组的时候,直接进行结构体数组的初始化工作 struct teacher teachers_two [] = { { "wangwu",30,{ "china","tianjin"}},{ "zhaoliu",40,{ "china","jiaozuo"}},{ "tianqi",50,{ "china","shenzhen"}}}; out_all_teachers(teachers_two,3); return 0; } void out_teacher(struct teacher tea){ printf("name:%s",tea.name); printf("age:%d ",tea.age); printf("country:%s ",tea.addr.country); printf("city:%s ",tea.addr.city); } void out_all_teachers(struct teacher teachers[],int num){ int i = 0; for(i = 0; i < num ; i++){ out_teacher(teachers[i]); printf("====================== "); } }
代码能够run,如果有需要的话,可以直接拉下来run一下,看看结构体数组是怎么进行初始化操作和使用的。谢谢大家的访问,如有写的不好的地方,希望大家能够及时的提出来,谢谢观看