How to dynamic allocate a two dimensional array

后端 未结 3 1664
星月不相逢
星月不相逢 2021-01-03 06:09

I would like to make a two dimensional array in C.

For example, I make an int type variable named place like this:

int *place;

I ha

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 07:02

    You need to do the following to allocate arr[x][y] of type int dynamically:

     int i = 0;
     int **arr = (int**)calloc(x, sizeof(int*));
     for(i = 0; i < x; i++)
          arr[i] = (int *) calloc(y, sizeof(int));
    

    The idea is to first create a one dimensional array of pointers, and then, for each array entry, create another one dimensional array.

提交回复
热议问题