简体   繁体   中英

Dynamically Allocate 2D Array on Input

I can allocate a 2D array using two variables.

eg

int x=10;
int y=2;
int **arr;
int=(int*)malloc*(x*y*sizeof(int))

or:

int x=10;
int y=2;
int **arr;
arr=(int*)malloc(x*sizeof(int))
for( i =0; i<x; i++ ){
    x[i]=(int*)malloc(y*sizeof(int))
}

But, what if I have just have 2D aray and I want to increase its size every time I input numbers?

eg

int **arr;
int x;
int y;
while ( scanf ("%d%d",&x,&y)){
    arr=(int*)malloc(sizeof(*arr)+1*sizeof(*arr)*1 * sizeof(int))
}

This example is obviously wrong. How can I achieve such result in C?

this will answers the first part of your question (aka situation one)

//situation one:  one continuous block of memory

//case one - preserving the original pointer (*arr)

int *realoc2d(int *arr,int old_x,int old_y,int new_x,int new_y){
    int x,y,cx,cy;
    int old_size,new_size;
    int *new_arr=NULL,
        *sav_arr;

    old_size=(old_x*old_y*sizeof(int));
    new_size=(new_x*new_y*sizeof(int));

    sav_arr=malloc(old_size);
    if(!sav_arr){
        //handle nomem error;
    }
    memcpy(sav_arr,arr,old_size);

    new_arr=realloc(arr,new_size);
    if(!new_arr){
        //handle nomem error;
    }

    cx=MIN(old_x,new_x);
    cy=MIN(old_y,new_y);

    for(x=0;x<cy;x++)
        for(y=0;y<cy;y++)
            new_arr[x+(y*new_y)]=sav_arr[x+(y*old_y)];

    free(sav_arr);

    return new_arr;

}


//case two - without preserving the original pointer (*arr)

int *realoc2d(int *arr,int old_x,int old_y,int new_x,int new_y){
    int x,y,cx,cy;
    int *new_arr;

    new_arr=malloc(new_x*new_y*sizeof(int));
    if(!new_arr){
        //handle nomem error;
    }

    cx=MIN(old_x,new_x);
    cy=MIN(old_y,new_y);

    for(x=0;x<cy;x++)
        for(y=0;y<cy;y++)
            new_arr[x+(y*new_y)]=arr[x+(y*old_y)];


    return new_arr;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM