【问题标题】:Reallocating **array重新分配**数组
【发布时间】:2017-05-09 16:18:19
【问题描述】:

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

这些是执行以下操作的 2 个函数;

//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");
}
}

【问题讨论】:

  • 但是我怎样才能改变缓冲区的大小,同时不删除其中的元素呢?还是应该将元素保存在数组中,然后将它们放回重新分配的元素中?谢谢
  • @xing 我已经修改了代码。你能检查一下我是否听从了你的建议。谢谢
  • 这是一个锯齿状数组,而不是二维数组!完全不同的数据类型!
  • @xing 所以我应该在函数adjustBuffer的开头设置buffer[0] = NULL吗?谢谢

标签: c arrays malloc realloc


【解决方案1】:

我猜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);
    }
}

检查 realloc 是否失败

//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]);
        }
    }
}

【讨论】:

  • 对不起。但它仍然给我一个分段错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 2012-11-10
  • 2012-06-17
  • 2012-10-23
相关资源
最近更新 更多