码迷,mamicode.com
首页 > 其他好文 > 详细

malloc()和free()

时间:2014-11-30 23:23:23      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:c语言

为数组动态分配存储空间

#include <stdio.h>

#include <stdlib.h>
int main(void)
{
double *ptd;
int max;
int number;
int i=0;
puts("What is the maximum number of type double entries?");
scanf("%d",&max);
ptd =(double *)malloc(max * sizeof (double));
if(ptd == NULL)
{
puts("Memory allocation failed.Goodbye.");
exit(EXIT_FAILURE);
}
puts("Enter the values(q to quit): ");
while(i<max && scanf("%1f",&ptd[i])==1)
i++;
printf("Here are your %d entries:\n.",number = i);


for(i=0;i<number;i++)
{
printf("%7.2f",ptd[i]);
if(i%7 == 6)
putchar(‘\n‘);
}
if(i%7 != 0)
{
putchar(‘\n‘);
}
puts("Done.");
free(ptd);
while(1);
return 0;

}


对应每一个malloc()调用,应该进行一次free()。函数free()的参数是先前malloc()返回的地址,它释放先前分配的内存。这样,所分配内存持续的时间是从调用malloc()分配内存开始,到调用内存给程序使用,每次调用free()分配释放内存一共再使用为止。

malloc()和free()

标签:c语言

原文地址:http://blog.csdn.net/u011046042/article/details/41628797

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!