c - 重新分配**数组

标签 c arrays malloc realloc

正在创建我的二维数组 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/

相关文章:

arrays - 在 Swift 3 中对 [Dictionary<String, Any>] 进行排序

c - C是命令式还是声明式编程语言

c - musl libc malloc 中的 adjustment_size 有何作用?

php - 如何组合从下拉列表中选择的日期/时间以在 MySQL 查询中使用?

c - "Pointer being freed was not allocated"发生在 mac 但不是在 windows 7

c - 调整整数数组大小时发出警告

C: 如何将经过 malloc 处理的指针传递给函数并释放它们?

C取消引用结构中的整数指针

服务器和客户端是否可以在同一个端口上发起通信并发送命令?

java - 利息数量