How to dynamic allocate a two dimensional array

后端 未结 3 1666
星月不相逢
星月不相逢 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 06:47

    Let place be a pointer to arrays,

    int (*place)[columns] = malloc(rows * sizeof *place);
    

    That gives you a contiguous block of memory (good for locality) that you can simply access with

    place[i][j] = whatever;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 07:04

    You could use a single 1d array as a 2d array by some smart indexing :

    Allocate memory :

    place = (int*) malloc(rows * columns * sizeof(int));
    

    To access place[i][j], use i and j as :

    place[ i*columns + j] = value ;
    
    0 讨论(0)
提交回复
热议问题