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");
}
}
但我怎麼能更改緩衝區的大小,並在同一時間不刪除其中的元素呢?或者我應該保存數組中的元素,然後把它們放回重新分配的一個?謝謝 – lfarr
@xing我修改了代碼。你能否檢查一下是否請你遵照你的建議。謝謝 – lfarr
這是一個鋸齒狀的陣列,而不是二維陣列!完全不同的數據類型! – Olaf