1、结构体的定义
在前面程序中,所用到的变量大多数都是相互独立的,没有内在联系,比如 int a; char c;都是相互独立的,但是有些情况需要把一些变量组合一起,比如,一个学生的名字,成绩,分数,学号等,都是不一样的数据类型,但是属于一个学生,如果定义了这些变量,他们也是相互独立的,不能反映这些变量的内在联系,有时候希望把这些属于一个人的数据组成一个组合数据。
数组也可以同时存放一组数据,那为什么数组不能存放这些数据呢?因为数组只能存放同一类型的数据,不能存放不同内型的数据,比如不能同时存放一个人的名字和分数,那么就需要结构体来解决这一类问题了。
struct Student{
int score;
char* name;
};
上面就自己声明了一个结构体,成员包含score和name,struct 是声明结构体类型必须用的关键字,不能少,这是一个包含score和name,还可以是其他类型的变量。
2、定义结构体变量
struct Student表示声明了一个结构体,struct Student stu就定义了一个结构体变量,这种定义结构体变量的方法和定义整型变量(int a)的方法差不多,(struct Student相当于int,stu就相当于a)。
定义了结构体变量,那么该怎么初始化和访问呢?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Student{
int number;
char name[128];
};
int main()
{
struct Student stu;
stu.number = 100;
strcpy(stu.name,"hello");
printf("分数等于:%d,名字等于:%s\n",stu.number,stu.name);
system("pause");
return 0;
}
上面代码中先定义了一个结构体变量struct Student stu, stu.number = 100表示给结构体中的number赋值100,strcpy(stu.name,“hello”),表示给结构体中的name拷贝hello,这就实现了结构体的初始化,printf(“分数等于:%d,名字等于:%s\n”,stu.number,stu.name),就表示对结构体成员的访问。
3、结构体中的一些运算
(".")是成员运算符,在所有运算符中优先级最高,
Student1.stu1 = Student2.stu2; (赋值运算)
sum = Student1.score2 + Student2.score2;(加法运算)
Student1.stu1++; (自加运算)
对于同类型的结构体变量可以相互赋值,(student1 = student2),表示把student2中的成员赋值给student1。