结构体
不同类型的数据是无法放在一个集合中,但生活中总能遇到一些问题,需要将它们放在一起;如:学生信息,酒店入住信息,火车票信息等;所以,C语言可以使用结构体,将这一切包含在一起。结构体是由结构体类型和成员名及变量名列表组成,如:
#include<stdio.h>
#include<windows.h>
struct Student
{
int num;
char name[20];
char sex;
int age;
int score;
}student1={1001,"张三",'M',20,90};
int main()
{
printf("num=%d\n",student1.num);
printf("name=%s\n",student1.name);
printf("sex=%c\n",student1.sex);
printf("age=%d\n",student1.age);
printf("score=%d\n",student1.score);
system("pause");
return 0;
}
上述结构体在声明类型的同时定义变量。
还可以光声明类型,在之后定义变量,或者不声明类型,直接定义变量。
上述代码中出现的"."是成员用算符,并且在所有成员用算符中优先级最高,顾可以将student1.num看做一个整体,相当于一个变量,同时也是结构体中的一个成员,可以使用一般变量所能用的各种用算。
结构体数组
结构体数组和数组差不多,一般数组中将同类型的元素存放数组中,而结构体数组中,每一个结构体相当于其中的元素。
#include<stdio.h>
#include<windows.h>
struct Student
{
int num;
char name[20];
char sex;
int age;
int score;
}student1[3] = { {1001,"张三",'M',20,90 } ,{1002,"李四",'M',18,88},{1003,"王五",'M',19,98} };
int main()
{
int n;
for (n = 0; n < 3; n++)
{
printf("num=%d\n", student1[n].num);
printf("name=%s\n", student1[n].name);
printf("sex=%c\n", student1[n].sex);
printf("age=%d\n", student1[n].age);
printf("score=%d\n", student1[n].score);
}
system("pause");
return 0;
}
结构体指针*
结构体指针就是指向构体变量的指针,将一个结构体变量的起始地址存放在一个指针变量中,那么,这个指针变量就指向这个结构体变量,指针变量的类型要与结构体相同。
#include<stdio.h>
#include<windows.h>
struct Student
{
int num;
char name[20];
char sex;
int age;
int score;
}student1 = { 1001,"张三",'M',20,90 };
int main()
{
struct Student*n;
n = &student1;
printf("num=%d\n", (*n).num);
printf("name=%s\n", (*n).name);
printf("sex=%c\n", n->sex);
printf("age=%d\n", n->age);
printf("score=%d\n", n->score);
system("pause");
return 0;
}
述代码中,(*n).
等价于n->
,为指向。