C语言高级进阶
结构体的创建和使用,指向结构体的指针的创建和使用,指向结构体的指针的数组的创建和使用学习内容
结构体属于c语言中的一种构造类型,用来存放一组不同类型数据的集合,下面我们学习结构体的创建和使用,结构体指针的创建和使用,以及指向结构体数组的指针的数组的创建和使用。学习产出
结构体的创建和使用相对简单,示例代码如下:
int main()
{
typedef struct
{
char *name;
int num;
int age;
char group;
float score;
} Stu, *pStu;
Stu stu1 = {"TomCat", 12, 18, 'A', 149.0};
pStu pstu = &stu1;
printf("name = %s, num = %d, age = %d, group = %c, score = %.2f\n", stu1.name, stu1.num, stu1.age, stu1.group, stu1.score);
printf("name = %s, num = %d, age = %d, group = %c, score = %.2f\n", pstu->name, pstu->num, pstu->age, pstu->group, pstu->score);
return 0;
}
运行结果如下:
指向结构体的指针的数组,乍一听起来非常绕口,我们采用剥洋葱由外向内去分析,想清楚后也不难理解,首先它是一个数组,这个数组的元素是指针变量,这个指针指向的数据是结构体,示例代码如下:
#include <stdio.h>
typedef struct
{
char *name;
int num;
int age;
float score;
char group;
} Stu , *pStu;
Stu stu[] = {
{"TomCat", 5, 13, 'C', 110},
{"JerryMouse", 3, 14, 'B', 130},
{"MickeyFish", 4, 16, 'A', 140},
{"GergerDog", 4, 17, 'A', 115},
{"DingDang", 4, 12, 'A', 135}
};
int main()
{
pStu pstu[5];
for(int i=0; i < sizeof(stu)/sizeof(stu[0]); i++)
{
pstu[i] = &stu[i];
printf("name = %s, num = %d, age = %d, group = %c, score = %.2f\n", pstu[i]->name, pstu[i]->num, pstu[i]->age, pstu[i]->group, pstu[i]->score);
}
return 0;
}
运行结果如下: