结构体
练习1
有n个学生的信息(包括学号、姓名、成绩),要求:
按照成绩的高低顺序输出各学生的信息
# include<stdio.h>
struct Student //声明结构体类型 struct Student
{
int num;
char name[20];
float score;
};
int main()
{
struct Student stu[5] = {
{10101,"mao",78},
{10103,"li",98.5},
{10106,"zhang",86},
{10108,"wang",73.5},
{10110,"tang",100} }; //定义结构体数组并初始化
struct Student temp; //定义结构体变量temp,用作交换时的临时变量
const int n = 5; //定义常变量n
int i, j, k;
printf("按成绩大小顺序输出:\n");
for (i = 0; i < n - 1; i++)
{
k = i;
for (j = i + 1; j < n; j++)
if (stu[j].score > stu[j].score) // 成绩比较
k = j;
temp = stu[k];
stu[k] = stu[i];
stu[i] = temp; //stu[k]和stu[i]元素互换
}
for (i = 0; i < n; i++)
{
printf("%6d\t%8s\t%6.2f\n", stu[i].num, stu[i].name, stu[i].score);
}
printf("\n");
return 0;
}
指向结构体变量的指针
练习2:
通过指向结构体变量的指针变量输出结构体变量中成员的信息
# include<stdio.h>
# include<string.h>
// C语言标准库中一个常用的头文件,在使用到字符数组时需要使用
int main()
{
struct Student
{
long num;
char name[50];
char sex;
float score;
};
struct Student stu_1; //定义struct Student类型的变量stu_1
struct Student * p; //定义指向struct Student类型数据的指针变量p
p = &stu_1; // p指向stu_1
stu_1.num = 10101; //对结构体变量的成员赋值
strcpy (stu_1.name,"lihuang"); //用字符串复制函数函数给stu_1.name赋值
stu_1.sex = 'M';
stu_1.score = 89.5;
printf("NO.:%ld\nname:%s\nsex:%c\nscore:%5.lf\n",
stu_1.num,stu_1.name,stu_1.sex,stu_1.score);
printf("NO.:%ld\nname:%s\nsex:%c\nscore:%5.lf\n",
(* p).num,(* p).name,(* p).sex,(* p).score);
return 0;
}
/*C语言允许把(* p).name 用 p->name 代替;
p->name表示p所指向的结构体变量中的name成员
“->”称为指向运算符
如果p指向一个结构体变量stu,以下3种用法都为等价:
1、stu.成员(如:stu.name)
2、(* p).成员名(如:(* p).name)
3、p->成员名(如: p->name)
*/
指向结构体数组的指针
练习3:
用3个学生的信息,放在结构体类型数组中,要求:
输出全部学生的信息
# include<stdio.h>
struct Student // 声明结构体类型 struct Student
{
long num;
char name[50];
char sex;
int age;
};
struct Student stu[3] = {
{10101,"mao",'M',78},
{10103,"li",'F',98},
{10106,"zhang",'M',86},
};
int main()
{
struct Student* p; //定义指向struct Student 结构体变量的指针变量
printf("学生的全部信息\n");
for (p = stu; p < stu + 3; p++)
{
printf("%5d %-20s %2c %4d\n",p->num,p->name,p->sex,p->age);
}
return 0;
}