I want to create a 2D array of ints, where the array's dimension is given at run time (not compile time). So far, I have been using:

int **ptr = malloc(m * sizeof(int*));

for (size_t i = 0; i < m; i++)
    ptr[i] = malloc(n*sizeof(int));

However I have read that this is not a good solution (waste of memory, can lead to memory leak, not having a real 2d array with all elements adjacent in memory, and other problems).

So, my question is, what is the correct way of creating a 2D array where its dimensions arent known at compile time?

2 Answers 2


it's generally recommended to minimize your heap usage. another alternative would be creating an array of pointers, perhaps on the stack, and allocating memory for your int arrays on the heap as necessary. for example:

int* ptrArray[NUM_OF_ARRAYS];
// as necessary (where i is a valid index)
ptrArray[i] = malloc(ARRAY_LENGTH * sizeof(int));

If you want to heap allocate, then this is the way I'd do it.

int width  = get_int("width: ");
int height = get_int("height: ");

int (*ar)[width] = calloc(height, width * sizeof(int));

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .