How does C allocate space for a 2D (3D…) array when using malloc?

后端 未结 3 1852
不思量自难忘°
不思量自难忘° 2020-12-06 08:40

I am having a problem understanding how C allocates space for a 2D (or more dimensional) array, especially when we use malloc and the like. Take the program in

3条回答
  •  自闭症患者
    2020-12-06 09:14

    Method 1 (pointers to buffers, non contiguous)

    You are correct, there is no guarantee the data will contiguous and in fact it most likely will not be. The top level array (rows) is simply a 1D array of pointers (each element is it's own pointer). These pointers each point to their own 1D array of actual objects. These buffers are only connected through pointers.

    linked

    /* allocation */
    int** array = malloc(sizeof(int*) * height)
    for (int y = 0; y < height; y ++)
    {
       array[i] = malloc(sizeof(int) * width);
    }
    /* indexing */
    int item = array[y][x];
    

    Method 2 (single buffer, contiguous)

    Another way to allocate 2D arrays is with a single buffer and then indexing it based on 2D coordinates. e.g. 8 * 8 = 64. Allocate a single 64 byte buffer and index = x + y * 8. This method stores data contiguously and it is much easier to allocate and deallocate than method 1.

    contiguous

    /* allocation */
    int* array = malloc(sizeof(int) * width * height)
    /* indexing */
    int item = array[x + y * width];
    

提交回复
热议问题