2017-05-09 35 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