您可以动态分配数组:
#include <stdlib.h>
char *a = malloc(100*sizeof(char));
if (a == NULL)
{
// error handling
printf("The allocation of array a has failed");
exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
当你想增加它的大小时:
tmp_a = realloc(a, 10000*sizeof(char));
if ( tmp_a == NULL ) // realloc has failed
{
// error handling
printf("The re-allocation of array a has failed");
free(a);
exit(-2);
}
else //realloc was successful
{
a = tmp_a;
}
Run Code Online (Sandbox Code Playgroud)
最后,记得在不再需要数组时释放已分配的内存:
free(a);
Run Code Online (Sandbox Code Playgroud)
基本上realloc(prt, size)返回指向具有指定大小的新内存块的指针,size并取消分配指向的块ptr.如果失败,则不释放原始内存块.请阅读这里和这里的进一步信息.
| 归档时间: |
|
| 查看次数: |
5863 次 |
| 最近记录: |