结构(Struct)[01]
结构类型(Struct)是一种允许程序员把一些不同类型的数据聚合成一个整体的数据类型。结构与数组的区别在于,数组元素必须是同类型的,而结构的成员(Member)可以是不同的数据类型。
结构类型的一般定义
Struct 结构名{
类型名 结构成员名1;
类型名 结构成员名2;
……
类型名 结构成员名n;
};
注意:
定义结构成员时所用的数据类型也可以是结构类型,从而形成结构类型的嵌套。
定义结构时花括号外面的分号不能省略,这是一个完整的语句。
1.结构体变量的定义
(1)先定义一个结构类型,再定义一个具有这种结构类型的变量,例如
struct stu { //先定义结构类型,结构名称为stu
char* name; //该结构的成员
int num;
int age;
char group;
float score;
}; //注意此处的分号不能省略
struct stu student1, student2; //定义student1和student2是具有stu形式的结构类型变量
(2)定义结构类型的同时定义结构体变量
struct stu { //先定义结构类型,结构名称为stu
char* name; //该结构的成员
int num;
int age;
char group;
float score;
} student1, student2; //定义student1和student2是具有stu形式的结构类型变量
注意:
若只需要student1, student2两个变量,后面不再使用结构名定义其他变量,则定义结构类型时可以不写出结构名:
struct {
char* name;
int num;
int age;
char group;
float score;
} student1, student2;
这样书写简单,但因为没有结构名,后面无法使用该结构类型定义新的变量。
2. 结构成员的引用和赋值
(1)结构类型通过操作符“.”来引用结构成员,也可以给成员赋值
#include<stdio.h>
int main()
{
struct
{
char* name;
int num;
int age;
char group;
float score;
}stu1;
stu1.name = "Tom"; //双引号引起实际代表一个指向某个字符串起始字符的指针
stu1.num = 12;
stu1.age = 18;
stu1.group = 'A'; //单引号引起实际代表A的ASCII码,是一个整数值
stu1.score = 136.5;
printf("%s的学号是%d, 年龄是%d, 在%c组,今年的成绩是%5.2f.\n", stu1.name, stu1.num, stu1.age, stu1.group, stu1.score);
return 0;
}
(2)在定义时整体赋值
struct stu {
char* name;
int num;
int age;
char group;
float score;
}student1, student2 = { "Tom",12,18,'A',123.6 };
注意:
整体赋值仅限于定义结构体变量时,在使用过程中只能对成员逐一赋值
(3)嵌套引用
#include<stdio.h>
struct Age {
int year;
int month;
int day;
};
struct student {
char* name;
char* num;
float score;
struct Age age; //嵌套定义名为age的Age结构体变量
};
int main()
{
struct student stu;
stu.name = "Tom";
stu.num = "16160001025";
stu.score = 135.8;
stu.age.year = 1998; //引用最底层成员变量
stu.age.month = 6;
stu.age.day = 12;
printf("%s的学号是%s,成绩是%5.2f,出生日期是%d年%d月%d日.",
stu.name, stu.num, stu.score, stu.age.year, stu.age.month, stu.age.day);
return 0;
}
(4)可以引用结构体变量成员的地址,也可以引用结构体变量的地址
#include<stdio.h>
struct Age {
int year;
int month;
int day;
};
struct student {
char* name;
char* num;
float score;
struct Age age; //嵌套定义名为age的Age结构体变量
};
int main()
{
struct student stu;
stu.name = "Tom";
stu.num = "16160001025";
scanf("%f,%d,%d,%d", &stu.score, &stu.age.year, &stu.age.month, &stu.age.day);
printf("%s的学号是%s,成绩是%5.2f,出生日期是%d年%d月%d日.",
stu.name, stu.num, stu.score, stu.age.year, stu.age.month, stu.age.day);
return 0;
}
(5)允许有相同类型的结构体变量相互赋值,其他情况不允许对结构体变量直接赋值
1. #include<stdio.h>
struct student {
int num;
float score;
}stuA, stuB;
int main()
{
stuA.num = 16160001025;
stuA.score = 136.5;
stuB = stuA;
printf("学号是%d,成绩是%5.2f", stuB.num, stuB.score);
return 0;
}