结构体
C语言允许用户自己建立由不同类型数据组成的组合型的数据结构,它称为结构体。
其一般形式为
Struct
{
成员表列
}变量名表列;
指定了一个无名的结构体类型,它没有名字(不出现结构体名)。一定要记得在变量名表列后边加分号。
说明:
(1)结构体类型与结构体变量是不同的概念,不要混同。只能对变量赋值、存取或运算,而不能对一个类型赋值、存取或运算。在编译时,对类型是不分配空间的,只对变量分配空间,
(2)结构体类型中的成员名可以与程序中的变量名相同,但二者不代表同一对象。例如,程序中可以另定义一个变量num,它与struct Student中的num是两回事,互不干扰。
结构体变量的初始化及其引用
在定义结构体变量时,可以对它初始化,即賦予初始值。然后可以引用这个变量,例如输出它的成员的值。
例9.1把一个学生的信息(包括学号、姓名、性别、住址)放在一个结构体变量中,然后输出这个学生的信息。
编写程序:
井include <stdio. h>
int main()
{
struct Student //声明结构体类型struct Student
{
long int num;
char mamne[20];
char sex;
char addr[20];
)a=({10101,"Li Lin",'M' ,"123 Beiing Road"}; //定义结构体变量a并初始化
pint'NO. ;%d\ mame: %\nex: hdaes.s ,a nm. name,a. sex.a. ad;
return 0;
}
注意
(1)对结构体变量的成员可以像普通变量一样进行各种运算( 根据其类型决定可以进行的运算)。例如:
Student1. Score= student2. score (赋值运算)
sum= studentl. score + student2. score; (加法运算)
student.age++ (自加运算)
由于“.”运算符的优先级最高,因此studentl. age++是对(student1. age)进行自加运算,而不是先对age进行自加运算。
(2)同类的结构体变量可以互相赋值,
如:
Student1=student2;
//假设student1和student2已定义为同类型的结构体变量
(3)可以引用结构体变量成员的地址,也可以引用结构体变量的地址。例如:
Scanf(“%d”,&student1. num); (输人&student1.num的值)
printf(" %o “,&student1); (输出结构体变量&student1的首地址)
但不能用以下语句整体读人结构体变量,例如:
scanf(“ %d,%s,%c, %d, %f,%s\n”,&student1);
结构体数组
- 定义结构体数组一般形式是
- ①struct结构体名
{成员表列}数组名[数组长度];
②先声明一个结构体类型(如struct Person),然后再用此类型定义结构体数组:结构体类型数组名数组长度];如:
struct P erson leader[3]; //leader是结构体数组名
- 对结构体数组初始化的形式是在定义数组的后面加上:= {初值表列};
如:
struct Person leader[3]= {"Li" ,0," Zhang ,0,"Sun" ,0};
例如:
#include<stdio.h>
struct Student
{
int id;
char name[20];
int score;
char sex[5];
}stu[3];
int main()
{
int i=0;
for(;i<3;i++){
printf("请输入学号:");
scanf("%d",&stu[i].id);
printf("请输入姓名:");
scanf("%s",stu[i].name);
printf("请输入分数:");
scanf("%d",&stu[i].score);
printf("请输入性别:");
scanf("%s",stu[i].sex);
}
for(i=0;i<3;i++)
{
printf("学号为:%d\n姓名为:%s\n成绩为:%d\n性别为:%s\n",stu[i].id,stu[i].name,
stu[i].score,stu[i].sex);
printf("-------------\n");
}
return 0;
}
结构体指针
#include<stdio. h>
#include<string. h>
int main()
{
struct Student
{
long num;
char name[20];
char sex;
float score;
};
Struct Student stu_1; //定义struct Student类型的变量stu_1
Student Student*p; //定义指问struct Student类型的指针变量p
p=&stu_1; //p指向stu_1;
stu_1.num=10101; //对结构体变量的成员赋值
strcpy(stu_1.name,”lilin”); //用字符串复制函数给stu_1.name赋值
stu_ 1. Sex= M' ;
stu_ 1. score =89.5;
printf(' No. :% ld\nname: %s\nsex: %c\nscore:%5. 1f\n" .
stu_ 1. num,stu_ 1. name,stu_ 1. sex,stu_ 1. score);
printf(" nNo. :% ldnname;% snsex: %cnscore:%5. 1fln" ,
( * p). num.( * p). name,(* p).sex, ( * p). score);
return 0;
}
如果p指向一个结构体变量Stu,以下三种用法等价
- Stu.成员名(如stu.num)
- (*p).成员名(如(*p).num)
- P->成员名(p->num)