dynamic allocation/deallocation of 2D & 3D arrays

后端 未结 4 2140
离开以前
离开以前 2020-12-01 05:10

I know about algorithms to allocate/deallocate a 2D array dynamically, however I\'m not too sure about the same for 3D arrays.
Using this knowledge and a bit of symmetry

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 05:17

    This is a version of the idea in the question but using only one malloc, inspired by the other answers. It allows intuitive use of the square brackets and easy cleaning. I hope it does not make any compiler implementation specific assumption.

    int main(int argc, char *argv[])
    {
      int **array, i, j;
      array = allocate2d(3, 4);
      for (i = 0; i < 3; i++)
      {
        for (j = 0; j < 4; j++)
        {
          array[i][j] = j + i + 1;
        }
      }
      for (i = 0; i < 3; i++)
      {
        for (j = 0; j < 4; j++)
        {
          printf("array[%d][%d] = %d\n", i, j, array[i][j]);
        }
      }
      free(array);
      return EXIT_SUCCESS;
    }
    
    int **allocate2d(int x, int y)
    {
      int i;
      int **array = malloc(sizeof(int *) * x + sizeof(int) * x * y);
      for (i = 0; i < x; i++)
      {
        array[i] = ((int *)(array + x)) + y * i;
      }
      return array;
    }
    

提交回复
热议问题