增加char数组的最大大小

Sow*_*mya 2 c arrays size max char

我在C中编写了一些代码,将char数组的最大大小设为100.它运行良好.但是当我将char数组的最大大小增加到10000时,它会给我分段错误(因为它超出了它的限制).有人能告诉我如何增加最大大小并存储长度为10000的字符串.

即如何将"char a [100]"作为"char a [10000]"并执行相同的代码????

Pyn*_*hia 8

您可以动态分配数组:

#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.如果失败,则不释放原始内存块.请阅读这里这里的进一步信息.