文章目录
- 一、基本概念
- 二、结构体定义的三种方式(声明后有不能忘了;号)
- 三、访问结构体成员
- 四、结构体数组
- 五、结构体的嵌套
一、基本概念
在C语言中,可以定义结构体类型,将多个相关的类型的变量包装成为一个整体使用。在结构体中的变量,可以是相同、部分相同,或完全不同的数据类型。在C语言中,结构体不能包含函数。
二、结构体定义的三种方式(声明后有不能忘了;号)
1、标准定义方式
#include <stdio.h>
struct student
{
int age;
float score;
char sex;
};
int main ()
{
struct student a={23, 98, 'f'};
printf("年龄:%d 分数:%.2f 性别:%c\n", a.age, a.score, a.sex );
return 0;
}
2、声明结构体时定义变量(不环保)
#include <stdio.h>
struct student
{
int age;
float score;
char sex;
} a={23, 87,'n'};
int main()
{
printf("年龄:%d 分数:%.2f 性别:%c\n", a.age, a.score, a.sex );
}
3、无类型名的结构体(此法最差,只能用一次)
#include <stdio.h>
struct
{
int age;
float score;
char sex;
} t={23, 98, 'f'};
int main ()
{
printf("年龄:%d 分数:%f 性别:%c\n", t.age, t.score, t.sex);
return 0;
}
4、用typedef给自定义的结构体加一个名字(typedef 已有类型 新类型名)
#include <stdio.h>
typedef struct student
{
int age;
float score;
char sex;
};
int main()
{
student a={23, 87,'n'};
printf("年龄:%d 分数:%.2f 性别:%c\n", a.age, a.score, a.sex );
}
三、访问结构体成员
用结构成员运算符点“ . ”就可以了:结构体变量名.成员名;
注意,点其结合性是自左至右的,它在所有的运算符中优先级是最高的。
1、一维数组
比如声明了一个结构体student,定义了一个变量stu:
struct student
{
char name[10];
int num;
int age;
float score[3];
char sex;
} stu;
在这个结构体中,如果要访问第二门课的分数,则需要这样访问:
scanf("%f", &stu.score[1]);
printf("%f", stu.score[1])
2、二维数组(同理)
比如声明了一个结构体student,定义了一个变量stu:
struct student
{
char name[10];
int num;
int age;
float score[3][2];
char sex;
} stu;
scanf("%f", &stu.score[1][1]);
printf("%f", stu.score[1][1])
3、其他更高维数组的用法都是一样的道理,以此类推。
四、结构体数组
比如声明了一个结构体student,定义了一个结构体变量数组stu[3]:
struct student
{
char name[10];
int num;
int age;
float score[3][2];
char sex;
} stu[3];
这里的stu就是一个结构体数组,包含了3个student类型的结构体变量。
接下来我们试着访问第3个结构体变量的第1门课第2次测验的成绩:
scanf("%f", &stu[2].score[0][1]);
printf("%f", stu[2].score[0][1])
五、结构体的嵌套
比如声明了一个结构体student,里面包含了一个结构体GoodStudent,里面声明了好学生的名字和成绩,同时定义了一个结构体变量数组stu[3]:
struct student
{
int num;
int age;
char sex;
struct GoodStudent
{
char name[10];
float score[3][2];
}
} stu[3];
此时要访问结构体GoodStudent好学生中的成绩,仍然是用“ . ”成员访问符来访问。
比如要访问第2个结构体变量的好学生的第2门课第1次测验的成绩:
scanf("%f", &stu[1].GoodStudent.score[1][0]);
printf("%f", stu[1].GoodStudent.score[1][0])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)