gpt4 book ai didi

c - 使用矩阵和自动化进行重新分配

转载 作者:行者123 更新时间:2023-11-30 17:18:41 26 4
gpt4 key购买 nike

我想知道如果我做类似的事情,为什么对 char* 或任何一维数组进行 realloc 会起作用oldpointer=realloc(oldpointer,newsize);

但是当我尝试使用 2D char* 数组时,它失败了。到处看看,我发现有时人们会使用NewPointer=realloc(oldpointer,newsize) 但如果它是唯一的用途,它对我来说没有用,因为我需要经常在循环中调整矩阵的列和行的大小(我必须填充一个字符串数组而不首先知道如何我将插入许多字符串,也不插入每个字符串的大小)

我用来尝试的代码是这样的,

void main(){
int max = 5, i,j;
char **matrix;
matrix=malloc(max*sizeof(char));
for(i=0;i<max;i++){
matrix[i]=malloc(max*sizeof(char));

}
matrix=realloc(matrix,max*2*sizeof(char));

strcpy(matrix[4],"we\0");
printf("%s",matrix[4]);

}

“./out”中的错误:realloc():下一个大小无效:0x00000000015c4010 ***已中止

最佳答案

问题是你的双指针无法容纳指针,因为你没有分配足够的空间。

matrix = malloc(max * sizeof(char));
/* which is exactly the same as
* matrix = malloc(max);
*/

应该是

matrix = malloc(max * sizeof(char *));
/* ^ max pointers, so sizeof a poitner */

那么如果你想要realloc(),你可以这样做

void *pointer;

pointer = realloc(matrix, 2 * max * sizeof(char *));
if (poitner == NULL)
handleFailure_OrExit_ButDoNot_Use_The_Realloced_Poitner();
matrix = pointer;

始终检查函数的返回值(如果返回值),例如 malloc()/calloc()/ realloc()以及通常的任何自定义实现”,失败时返回NULL

关于c - 使用矩阵和自动化进行重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29103265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com