C语言中如何动态增加内存空间

C语言中如何动态增加内存空间

动态增加内存空间 可以用 realloc 函数。函数原型是。
void* realloc (void* ptr, size_t size);
例如,你第一次用 malloc 函数 动态分配了空间,随着一步步运算,觉得空间不够,需要加大空间,与此同时,原先空间里的数据需保留并还要继续使用,这时需要用 realloc,它能满足此需要。
下面是完整的程序例子。告诉使用 realloc 的窍门。
#include <stdio.h> /* printf, scanf, puts */
#include <stdlib.h> /* realloc, free, exit, NULL */
int main ()
{
int input,n;
int count = 0;
int* numbers = NULL;
int* more_numbers = NULL;
do {
printf ("Enter an integer value (0 to end): ");
scanf ("%d", &input);
count++;
more_numbers = (int*) realloc (numbers, count * sizeof(int));
if (more_numbers!=NULL) {
numbers=more_numbers;
numbers[count-1]=input;
}
else {
free (numbers);
puts ("Error (re)allocating memory");
exit (1);
}
} while (input!=0);
printf ("Numbers entered: ");
for (n=0;n<count;n++) printf ("%d ",numbers[n]);
free (numbers);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-10-09
有一个malloc函数,专门用来进行动态内存管理的
相似回答