本次内容:结构体变量与指针 教学目的:掌握指向结构体变量、数组及作为函数参 数的指针的定义和引用。 重点:结构体变量与指针使用指针访问结构体成员和 访问不同对象的指针类型定义,结构体指针作为函数 参数。 难点:使用结构体指针变量访问结构体成员,作为函 数参数。 预习: 结构体类型定义、结构体变量定义、结构体成员访问、 结构体数组定义和引用
本次内容:结构体变量与指针 教学目的:掌握指向结构体变量、数组及作为函数参 数的指针的定义和引用。 重点:结构体变量与指针使用指针访问结构体成员和 访问不同对象的指针类型定义,结构体指针作 为函数 参数。 难点:使用结构体指针变量访问结构体成员,作为函 数参数。 预习: 结构体类型定义、结构体变量定义、结构体成员访问、 结构体数组定义和引用
、指向结构体变量的指针 结构体变量的指针:结构体变量所占单元的起始地址。 定义方法: 如: struct stud_type I char name[10; int agei char sex; maino struct stud_type student, *p; p=&student; p指向结构体变量 student 如:(*p)name则指向成员name不能写 pname 或:p->name,p->age“-”运算级最高。 或: int"pt; pt=& student.age按成员类型定义 指针
一、指向结构体变量的指针 结构体变量的指针:结构体变量所占单元的起始地址。 定义方法: 如:struct stud_type { char name[10]; int age; char sex; }; main() { struct stud_type student,*p; p=&student; : p指向结构体变量student。 如:(*p).name 则指向成员name 不能写p.name. 或:p->name , p->age “->”运算级最高。 或:int *pt; pt=&student.age 按成员类型定义 指针
注:1、指向结构体变量的指针,是指向结构体变量的, 即是结构体变量的首地址。 2、当指向成员时,用(*P)name或P>name 不能用 Pname表示,此方式是变量的成员表示 3、可以按成员类型定义成员指针 指向结构体数组的指针 即将结构体数组地址赋给结构体指针变量。 如: struct stud_type char namekO int age; char sex Parr 5l,"pi p=art P指向数组的第一个元素。 例:710(下页)
注:1、指向结构体变量的指针,是指向结构体变量的, 即是结构体变量的首地址。 2、当指向成员时,用 (* P).name 或 P->name 不能用 P.name表示,此方式是变量的成员表示。 3、可以按成员类型定义成员指针。 二、指向结构体数组的指针 即将结构体数组地址赋给结构体指针变量。 如:struct stud_type { char name[10]; int age; char sex; }arr[5],*p; p=arr; P指向数组的第一个元素。 例:7.10(下页)
# include“ steib.h include“ stdio h struct stud-type Ichar name[; long num; int agei char sex; float scorer maino I struct stud_type student 31, int k; char numstr[20; for( ke0, p=student;p<studen+3; p++, k++) 【gets( studen[ k name gets(numstr)ip-pnum=atol (numstr) gets(numstr)ip-page=atoi((numstr) p->sex=( getchar(; gets(numstrip->score=atof(numstr); 1
#include “stdlib.h” #include “stdio.h” struct stud_type {char name[20]; long num; int age; char sex; float score; }; main() { struct stud_type student[3],*p; int k; char numstr[20]; for ( k=0,p=student;p<studen+3;p++,k++) { gets(studen[k].name); gets(numstr);p->num=atol(numstr); gets(numstr);p->age=atoi((numstr); p->sex=getchar( );getchar( ); gets(numstr);p->score=atof(numstr); }
for( k0, p=student;p<student+3;p++, k++) printf(%3d %-20s", k, p-pname); printf(%81d %6d",p->num, p-page); printf(3c %6.2fn",p->sex, p->score); 、指向结构体变量的指针作为函数参数 例711 nclude“ steib. h # nclude“ stdio.h struct stud_type [char name[201; long num; int age; char sex; float score
for( k=0,p=student;p<student+3;p++,k++) { printf(“%3d %-20s”,k,p->name); printf(“%81d %6d ”, p->num,p->age); printf(“3c %6.2f\n”,p->sex,p->score); } } 三、指向结构体变量的指针作为函数参数 例7.11 #include “stdlib.h” #include “stdio.h” struct stud_type {char name[20]; long num; int age; char sex; float score; };