2017-05-09 38 views
0

正在创建我的2d数组char **缓冲区。 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"); 
} 
} 
+0

但我怎么能更改缓冲区的大小,并在同一时间不删除其中的元素呢?或者我应该保存数组中的元素,然后把它们放回重新分配的一个?谢谢 – lfarr

+0

@xing我修改了代码。你能否检查一下是否请你遵照你的建议。谢谢 – lfarr

+1

这是一个锯齿状的阵列,而不是二维阵列!完全不同的数据类型! – Olaf

回答

0

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

对不起。但它仍然给我一个分段错误 – lfarr