gpt4 book ai didi

c - 重新分配**数组

转载 作者:行者123 更新时间:2023-11-30 16:46:06 25 4
gpt4 key购买 nike

正在创建我的二维数组 char **缓冲区。 malloc 部分有效。 realloc 部分正在生成段错误。

这两个函数执行以下操作;

//sets up the array initially
void setBuffer(){
buffer = (char**)malloc(sizeof(char*)*buf_x);

for(int x=0;x<buf_x;x++){
buffer[x] = (char *)malloc(sizeof(char)*buf_y);
}

if(buffer==NULL){
perror("\nError: Failed to allocate memory");
}
}

//changes size
//variable buf_x has been modified
void adjustBuffer(){
for(int x=prev_x; x<buf_x;x++) {
buffer[x] = NULL;
}

buffer=(char**)realloc(buffer,sizeof(char*)*buf_x);

for(int x=0; x<buf_x;x++){
buffer[x] = (char*)realloc(buffer[x],sizeof(char)*buf_y);
strcpy(buffer[x],output_buffer[x]);
}
if(buffer == NULL){
perror("\nError: Failed to adjust memory");
}
}

最佳答案

我猜 buf_x 是全局的。
您需要存储原始大小并将其传递给函数。
如果添加了元素,则需要将新元素设置为 NULL,以便 realloc 将会成功。

//variable buf_x has been modified
void adjustBuffer( int original){
buffer=realloc(buffer,sizeof(char*)*buf_x);
for(int x=original; x<buf_x;x++){
buffer[x] = NULL;//set new pointers to NULL
}
for(int x=0; x<buf_x;x++){
buffer[x] = realloc(buffer[x],sizeof(char)*buf_y);
}
}

检查重新分配是否失败

//variable buf_x has been modified
void adjustBuffer( int original){
if ( ( buffer = realloc ( buffer, sizeof(char*) * buf_x)) != NULL) {
for ( int x = original; x < buf_x; x++) {
buffer[x] = NULL;//set new pointers to NULL
}
for ( int x = 0; x < buf_x; x++){
if ( ( buffer[x] = realloc ( buffer[x], strlen ( output_buffer[x]) + 1)) == NULL) {
break;
}
strcpy(buffer[x],output_buffer[x]);
}
}
}

关于c - 重新分配**数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43875032/

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