在C语言中重新分配二维数组
因此,我看到了一些与此相关的问题,但没有一个是真正的描述性问题,也没有一个能向我解释这一点 所以我试图改变字符串数组中有多少字符串,例如array[3][155] realloc()插入数组[4][155] 创建4个字符串,每个字符串包含155个字符,然后可以通过执行fgets(数组[4],155,stdin)来修改这些字符; 然后打印出新的数组 我在这里的尝试在C语言中重新分配二维数组,c,arrays,realloc,C,Arrays,Realloc,因此,我看到了一些与此相关的问题,但没有一个是真正的描述性问题,也没有一个能向我解释这一点 所以我试图改变字符串数组中有多少字符串,例如array[3][155] realloc()插入数组[4][155] 创建4个字符串,每个字符串包含155个字符,然后可以通过执行fgets(数组[4],155,stdin)来修改这些字符; 然后打印出新的数组 我在这里的尝试 #include <stdio.h> #include <stdlib.h> #include <un
#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++;
}
}
您收到的错误消息非常好:
pointer being realloc'd was not allocated
如果要使用realloc
,则需要向其传递空指针或使用类似malloc
或realloc
的函数动态分配的指针。您传递的指针指向存储在堆栈上的数组,该数组与堆不同,没有重新分配功能
我还看到您正在调用参数为4的realloc
。realloc
函数无法知道数组的结构或元素的大小,因此需要传递所需的字节数
此外,您还需要将realloc
返回的指针存储在某个位置,最好在检查它是否为NULL之后。如果realloc返回一个非空指针,您应该忘记传递给它的原始指针
pointer being realloc'd was not allocated