0
点赞
收藏
分享

微信扫一扫

周游C语言教程13 - 结构体

兵部尚输 2022-02-06 阅读 64

周游C语言教程13 - 结构体

这是周游C语言的第十三篇教程,你将在这篇文章里认识结构体。

结构体

结构体就是由若干个数据类型组合而成的数据类型,它本身也是一个数据类型。因为通常一个物体不仅仅只有一个属性,因此我们可以通过构筑结构体来表示一个对象。

我们以一个学生的成绩举例,首先一个学生有<名字>,有<学号>,然后我们假设这个学生考了数学和语文两门课,每门课有<成绩>和<排名>这两个属性。我们首先对每门课进行抽象

struct course
{
	int score; // 分数
	int ranking; // 排名
};

然后我们对学生进行抽象

struct stu
{
	char name[16];
	int id;
	struct course chinese;
	struct course math;
};

从上述代码我们可以看出结构体中可以继续嵌入结构体。

结构体变量

和枚举相同,结构体变量同样有三种定义方式。
1、先定义结构体名再定义变量

struct course
{
	int score; // 分数
	int ranking; // 排名
};
struct course math;
struct course chinese;

2、定义结构体名时直接定义变量

struct course
{
	int score; // 分数
	int ranking; // 排名
}math,chinese;

3、定义结构体时忽略名称直接定义变量

struct
{
	int score; // 分数
	int ranking; // 排名
}math,chinese;

但是请注意,只有结构体名称相等的编译器才认为是同一种结构体,上述三种定义方式只有第一第二种叫struct course,因此他们是同一种结构体,而第三种忽略了名称,所以不是同一种。

使用结构体

用变量的方式直接访问结构体时可以使用.的方式访问结构体元素,比如上述的math.score
如果是用指针的方式则使用->访问结构体元素,比如pMath->score

#include <stdio.h>
struct course
{
	int score; // 分数
	int ranking; // 排名
};

int main()
{
	struct course math;
	struct course chinese;
	struct course* pMath;
	pMath = &math;

	pMath->ranking = 100;
	pMath->score = 80;
	chinese.ranking = 85;
	chinese.score = 85;
	

	printf("语文的成绩是%d,排在第%d名\n",chinese.score,chinese.ranking);
	printf("数学的成绩是%d,排在第%d名\n", pMath->score, pMath->ranking);
	return 0;
}

结构体作为函数参数

结构体其本质也是一种数据类型,因此它也能作为函数参数,但是由于形式参数的特性,如果函数体内需要改变结构体的值,我们通常会传入结构体指针。

#include <stdio.h>
#include <string.h>
struct course
{
	int score; // 分数
	int ranking; // 排名
};
struct stu
{
	char name[16];
	int id;
	struct course chinese;
	struct course math;
};
void set_stu_score(struct stu* student, struct course chinese, struct course math)
{
	student->chinese.ranking = chinese.ranking;
	student->chinese.score = chinese.score;
	student->math.ranking = math.ranking;
	student->math.score = math.score;
}
int main()
{
	struct stu student;
	struct course math;
	struct course chinese;

	strcpy(student.name, "Tom");
	student.id = 1;
	math.ranking = 100;
	math.score = 80;
	chinese.ranking = 85;
	chinese.score = 85;
	set_stu_score(&student,chinese,math);
	

	printf("%s的语文的成绩是%d,排在第%d名\n", student.name,student.chinese.score,student.chinese.ranking);
	printf("%s的数学的成绩是%d,排在第%d名\n", student.name,student.math.score, student.math.ranking);
	return 0;
}
举报

相关推荐

0 条评论