[英]Dynamically allocate memory for array in C
我已将内存分配给数组(使用malloc
),但是如果需要更多空间怎么办,是否可以稍后在程序中扩展数组? 还是创建一个新数组并使第一个数组中的最后一个元素指向新数组?
我知道realloc
会更容易使用,但是我试图仅使用malloc
来做到这一点。
通用算法是
allocate array of 100
while more input
if no-room-in-array
allocate another array 100 bigger than the current array
copy values from current array into newly created array
free(current array)
current array = newly created array (the one you copied into)
// now there will be room, so
put input in array
是的,您可以使用realloc()
。 但是,在将返回值分配给原始指针之前,请务必检查其返回值。 看到这里: https : //stackoverflow.com/a/1986572/4323
错误的大小传递给malloc()
。
代码应该传递n * sizeof(int)
而不是传递n
个字节。
// int *array1=(int *)malloc(100);
int *array1 = malloc(100 * sizeof *array1);
// int *newArray=(int *)malloc(size+100);
int *newArray = malloc((size+100) * szeof *newArray);
其他想法包括
1)无需投放
int *array1 = (int *) malloc(...;
int *array1 = malloc(...);
2)用memcpy()
简化
// for(i=0; i<size; i++) newArray[i]=array1[i];
memcpy(newArray, array, size * sizeof *newArray);
3)确保free()
4) new
是一个C ++运算符,这是C,使用malloc()
。
5)使用size_t
而不是int
作为size
。
6)指数增长,而不是线性增长
// int *newArray=(int *)malloc(size+100);
size_t newsize = size*3/2;
int *newArray = malloc(newsize);
7)检查malloc()
失败
int *newArray = malloc(newsize);
if (newArray == NULL && newsize > 0) Handle_Failure();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.