defining a 2D array with malloc and modifying it

前端 未结 7 1169
陌清茗
陌清茗 2020-12-01 13:43

How do i define a 2D array using malloc ? (lets say 10X20).

second, can i increase number of rows or cols without creating a new increased array and copying all data

7条回答
  •  时光取名叫无心
    2020-12-01 14:03

    While malloc() does not directly support multi-dimensional arrays, there are workarounds, such as:

    int rows = 10;
    int cols = 30;
    int *array = malloc(rows * cols * sizeof(int));
    
    // Element (5,6)
    int x = 5;
    int y = 6;
    int element = array [ x * cols + y ];
    

    While this isn't directly a 2D array, it works, and in my opinion it's the simplest. But if you want to use the [][] syntax instead, you would have to make pointers to pointers, for instance:

    int rows = 10;
    int cols = 30;
    // Rows
    int **array = malloc(rows * sizeof(int*));
    // Cols
    int i;
    for(i = 0; i < rows; i++)
      array[i] = malloc(cols * sizeof(int));
    
    // Element (5,6)
    int x = 5;
    int y = 6;
    int element = array[x][y];
    

提交回复
热议问题