[英]Reallocating **array
我的2d數組char ** buffer正在創建。 malloc部分起作用。 重新分配部分正在生成分段錯誤。
這些是執行以下操作的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");
}
}
我猜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]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.