所以我看到了一些与此相关的问题,但没有一个问题具有太多的描述性或可以向我解释它 所以我试图更改字符串数组中有多少个字符串,例如 array[3][155] realloc() 到数组[4][155] 创建 4 个字符串,每个字符串包含 155 个字符,然后可以通过 fgets(array[4], 155, stdin); 进行修改 然后打印出新的数组
我在这里的尝试
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main () {
int arrays = 3;
int pnm = 0;
char array[arrays][155]; //Default size is 3 you can change the size
strcpy(array[0], "Hello from spot 0\n");
strcpy(array[1], "Sup from spot 1\b");
strcpy(array[2], "Sup from spot 2");
while(pnm != arrays) {
printf("Word %d: %s", pnm, array[pnm]);
pnm++;
}
realloc(array, 4);
strcpy(array[3], "Sup from spot 3!");
printf("The array is now.\n");
pnm = 0;
while(pnm != 4) {
printf("%s", array[pnm]);
pnm++;
}
}
在控制台输出
bash-3.2$ ./flash
Word 0: Hello from spot 0
flash(1968,0x7fff70639000) malloc: *** error for object 0x7fff5828f780: pointer being realloc'd was not allocated
*** set a breakpoint in malloc_error_break to debug
Word 1: Sup from spot Word 2: Sup from spot 2Abort trap: 6
bash-3.2$
最佳答案
您收到的错误消息非常好:
pointer being realloc'd was not allocated
如果您要使用realloc
,您需要向它传递一个 NULL 指针或一个使用 malloc
等函数动态分配的指针。或realloc
。您传递的指针指向存储在堆栈上的数组,堆栈与堆不同,并且不具有重新分配功能。
我还看到您正在调用realloc
参数为 4。realloc
函数无法了解数组的结构或其元素有多大,因此您需要传递所需的字节数。
此外,您还需要存储 realloc
返回的指针某处,最好是在检查它不为 NULL 之后。如果 realloc 返回一个非 NULL 指针,您应该忘记传递给它的原始指针。
关于c - 在 C 中重新分配二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43243296/