1 / 35
文档名称:

精品PPT课件----第10章 动态数组与链表.ppt

格式:ppt   页数:35
下载后只包含 1 个 PPT 格式的文档,没有任何的图纸或源代码,查看文件列表

如果您已付费下载过本站文档,您可以点这里二次下载

精品PPT课件----第10章 动态数组与链表.ppt

上传人:wz_198613 2014/10/30 文件大小:0 KB

下载得到文件列表

精品PPT课件----第10章 动态数组与链表.ppt

文档介绍

文档介绍:第十章 动态数组与链表
引入问题
1. 求某班级(30人)中所有学生的成绩平均分。
float a[30]
2. 求任意一个班级(人数不定)中所有学生的成绩平均分。
方法:求最大班级人数(假设100),float a[100]
解决办法:能不能根据我输入的班级人数,来自动的确定数组长度。
缺点:浪费内存空间
静态分配
动态分配
动态存储分配函数
malloc函数(memory allocation)
void *malloc(int n);
calloc函数(count allocation)
void *calloc(int count,int n);
free函数
void free(void *ptr);
realloc函数(reallocation)
void *realloc(void *p,int n);

int *p,n;
Scanf(“%d”,&n);
p= malloc(n);
(int*)
int a[10];
40
int *p,count,n;
Scanf(“%d%d”,&count,&n);
p= calloc(count,n);
(int*)
10 4
int *p,n;
Scanf(“%d”,&n);
p= malloc(n);
p= realloc(p,40);
(int*)
10
(int*)
free(p)
#include <>
#include <>
void main()
{
float *p,s=0;
int num,i;
scanf("%d",&num);
p=(float*)malloc(num);
for (i=0;i<num;i++)
scanf("%f",p+i);
for (i=0;i<num;i++)
printf("%",*(p+i));
for (i=0;i<num;i++)
s=s+(*(p+i));
printf("\n%f",s/num);
}
2. 求任意一个班级(人数不定)中所有学生的成绩平均分。
free函数
void free(void *ptr);
#include<>
#include<>
#include<>
void main()
{
char *str;
str=(char *)malloc(10*sizeof(char));
strcpy(str,"china");
printf("String is %s\n",str);
free(str);
printf("String is %s\n",str);
}
#include<>
#include<>
#include<>
void main()
{

char *str;
char* m();
str=m();
printf("String is %s\n",str);
}
char* m()
{
char * str;
str=(char *)malloc(10*sizeof(char));
strcpy(str,"china");
printf("String is %s\n",str);
// free(str); //考察str所指向的空间什么时候被回收?
printf("String is %s\n",str);
return str
}
动态内存分配函数是在整个程序运行完毕时,才回收内存;但是函数的局部变量是在本函数执行完毕时就回收。使用了free函数,就可以在执行到该语句时,就能够回收该内存空间。
realloc函数
void *realloc(void *p,int n);
#include <>
#include <>
#include <>
main()
{char *p;
p=(char *)malloc(100);
if(p) printf("Memory Allocated at: %x",p);
else printf("Not Enough Memory!\n");
strcpy(p,"hello world");
p=(char *)realloc(p,600);
if(p) printf("Memory Reallocated at: %x",p);
else printf("Not Enough Memory!\n");
free(p);}
#include <>
#in