70 likes | 202 Views
本次内容:结构体变量与指针 教学目的:掌握指向结构体变量、数组及作为函数参数的指针的定义和引用。 重点:结构体变量与指针使用指针访问结构体成员和访问不同对象的指针类型定义,结构体指针作 为函数参数。 难点:使用结构体指针变量访问结构体成员,作为函数参数。 预习: 结构体类型定义、结构体变量定义、结构体成员访问、结构体数组定义和引用 。.
E N D
本次内容:结构体变量与指针教学目的:掌握指向结构体变量、数组及作为函数参数的指针的定义和引用。重点:结构体变量与指针使用指针访问结构体成员和访问不同对象的指针类型定义,结构体指针作 为函数参数。难点:使用结构体指针变量访问结构体成员,作为函数参数。预习:结构体类型定义、结构体变量定义、结构体成员访问、结构体数组定义和引用。
一、指向结构体变量的指针结构体变量的指针:结构体变量所占单元的起始地址。定义方法:如: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不能用 P.name表示,此方式是变量的成员表示。3、可以按成员类型定义成员指针。二、指向结构体数组的指针 即将结构体数组地址赋给结构体指针变量。如:struct stud_type { char name[10]; int age; char sex; }arr[5],*p; p=arr;P指向数组的第一个元素。例:7.10(下页)
#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( 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;};
main(){ void list (struct stud_type *pt ) struct stud_type student[3]; int k; char numstr[20]; for ( k=0; k<3;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 ( k=0 ; k<3 ; k++ ) list (&student[k]);void list (struct stud_type *p ){ printf(“%-20s”, p->name); printf(“%81d %6d ”, p->num,p->age); printf(“3c %6.2f\n”,p->sex,p->score);}
小结:1、指向结构体变量的指针(1)指向结构体变量的指针,是指向结构体变量的,即是结构体变量的首地址。(2)当指向成员时,用 (* P).name 或 P->name不能用 P.name表示,此方式是变量的成员表示。(3)可以按成员类型定义成员指针。2、指向结构体数组的指针3、指向结构体变量的指针作为函数参数4、程序中引用的 ch=getchar( )或getchar( )的作用是“吃掉”上一个“回车”符。