第9章C语言 结构体和共用体.ppt
文本预览下载声明
第 9 章 结构体与共用体;num;一般形式:
struct 结构体名 { 结构体成员表 };
例如:
struct student
{ int number;
char name[20];
char sex;
int age;
float score;
char addr[30];
};;struct date
{ int year; int month; int day; };;9.2 结构体类型变量
9.2.1 结构体类型变量的定义
1 先定义类型,再定义变量。
struct 结构体名 变量名等;
2.在定义结构体类型的同时定义变量
struct 结构体名
{成员表}变量名表列;
3.直接定义结构体类型变量
struct
{成员表}变量名表列;;9.2.2 结构体变量的引用
结构体变量名.成员名
例如:
struct date
{ int year;
int month;
int day;
}
struct example
{ int num;
char name[20];
struct date bir;
} s1, s2;;【例9.1】输入某学生的姓名、年龄和5门功课成绩,计算平均成绩并输出。;9.3 结构体数组
9.3.1 结构体数组的定义与初始化
1.结构体数组的定义
例如:
struct student
{ int num;
char name[20];
char sex;
int age;
float score[3];
};
struct student stu[10];
; 9.3.2 结构体数组的引用
下面通过一个例子来说明结构体数组的引用。
【例9.2】输入3个复数的实部和虚部放在一个结构体数组中,根据复数模由大到小顺序对数组进行排序并输出。(注:复数的模=sqrt(实部*实部+虚部*虚部))
;运行结果:
3 2↙
1 1↙
5 4↙
5.00+4.00i
3.00+2.00i
1.00+1.00i;9.4 结构体和指针
1.结构体指针变量的定义
例如:
struct student
{ int num;
char name[15];
float score[3];
}stu[10], x, *p;
p=x; ; 9.5 结构体和函数
9.5.1 结构体作函数参数
1.结构体变量作函数参数
【例9.4】输入两个复数,比较这两个复数模是否相等。
; 2.结构体指针作函数参数
【例9.5】编写按复数模从小到大排序函数。;void main()
{ struct comp a[N]; int i;
printf(Input complex:\n);
for(i=0;iN;i++)
{ scanf(%f%f,a[i].x,a[i].y);
a[i].m=sqrt(a[i].x*a[i].x+a[i].y*a[i].y);
}
sort(a,N);
printf(Output complex:\n);
for(i=0;iN;i++)
printf( %.1f%+.1fi,a[i].x,a[i].y);
printf(\n);
};9.5.2 返回结构体的函数
1.返回结构体数据的函数
函数可以带回一个结构体类型的数据给主调函数。
【例9.6】输入一批复数,查找并输出模最大的复数。编写函数完成查找功能。;#define N 5
#includestdio.h
#includemath.h
struct comp
{ float x,y;
float m;
};
struct comp find(struct comp p[], int n)
{ int i,k=0;
float t=p[0].m;
for(i=1;in;i++)
if(tp[i].m)
{ t=p[i].m; k=i; }
return p[k];
};2.返回结构体指针的函数;9.6 链表(简介) ;9.6.2 动态存储分配函数
1.malloc函数
函数原型:
void *malloc(unsigned int size);
使用方法:
例如:
char *x;
x=(char*)malloc(10);
;2.calloc函数
函数原型:
void *calloc(unsigned int n,unsigned int size);
使用方法:
例如:
float *x;
x=(float*)calloc(10,
显示全部