c语言指针课件.pptVIP

  • 14
  • 0
  • 约2.03万字
  • 约 81页
  • 2019-08-17 发布于浙江
  • 举报
【例9.17】 采用“引用传递”的方式,用指向结构体 的指针变量作参数,在input函数中输入并计算平均成 绩,在main函数输出。 #define N 4 #includestring.h #define FMT %5d %-11s%5d%8d%8d%10.1f\n struct st { int num; char name[11]; int s[3]; float aver; }; void input(struct st *p) { scanf(%d%s%d%d%d,p-num,p-name,p-s[0],p-s[1],p-s[2]); p-aver=(p-s[0]+p-s[1]+p-s[2])/3.0; } main() { struct st a[N],*p=a; printf(Input student:number name score1 score2 score3\n); while(pa+N) input(p++); printf(number name score1 score2 score3 average\n); for(p=a;pa+N;p++) printf(FMT,p-num,p-name,p-s[0],p-s[1],p-s[2],p-aver); } 指针与链表 链表可以动态的进行存储分配 1249 head 1249 A 1356 1356 B 1475 1475 C 1021 1021 D NULL head: 头指针,存放一个地址,指向链表中的第一个元素. 每一个元素称为一个“结点”,每个结点都包括两部分: 1.用户需要的实际数据; 2.下一个结点的地址. 表尾: 它的地址部分放一个“NULL”,链表到此结束. 可用结构体类型的变量来存储链表中的结点元素. 1249 head 1249 A 1356 1356 B 1475 1475 C 1021 1021 D NULL 每一个结点中存放地址的部分可用指针来实现. 例: struct student { int num; float score; struct student *next; }; 简单静态链表 # define NULL 0 struct student { long num; float score; struct student *next; }; main( ) { struct student a,b,c,*head,*p; a.num=9901; a.score=89.5; b.num=9903; b.score=90; c.num=9905; c.score=85; head=a; a.next=b; b.next=c; c.next=NULL; p=head; do { printf(“%ld %5.2f \n”,p-num,p-score); p=p-next; }while(p!=NULL); } a num score next b c head p 9901 89.5 9903 90 9905 85 a b c NULL a b c NULL 动态链表 处理动态链表所需的函数 1. malloc 函数 void *malloc (unsigned int size); 作用是: 在内存的动态存储区分配一个长度为size的连续空间 原型说明在“stdlib.h”头文件和“alloc.h”头文件中 2.calloc函数 void *calloc(unsigned n,unsigned size); 作用是: 在内存的动态区分配n个长度为size的连续空间. 3. free函数 void free(void *p); 作用是: 释放由p指向的内存区. typedef struct Node { int data; struct Node *next; }Node; 链表的插入操作 s e ∧ × ①s-next=pre-next; ②pre-next=s; 顺序可以 颠倒吗? a1 a2 ai-1 ai an ∧ … … pre h void InsList(Node *L,int i,int e) { Node *pre,*s; int k=0; pre=L; while(pre!=NUL

文档评论(0)

1亿VIP精品文档

相关文档