Search code examples
cmultidimensional-arraydynamic-memory-allocation

What is the easiest way to dynamically allocate memory for 2d array?


I am curious how the best programmers in the world allocate memory for a 2d array. Any tips and advice will be much appreciated.

PS I am just a student trying to learn.


Solution

  • Use array pointers

    {
        size_t rows = 10;
        size_t cols = 50;
    
        int (*array)[cols] = malloc(rows * sizeof(*array));
    
        /* ... */
    
        free(array);
    }