like this : int (*arr)[M] = malloc(sizeof(int[N][M]));

arr is pointer to int[M].

use like arr[0][M-1];

and free(arr);

Answer from BLUEPIXY on Stack Overflow
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › arrays.html
2.5.1. Single-Dimensional Arrays
Like 1D dynamically allocated arrays, the pointer variable for a 2D array is allocated on the stack. That pointer is then assigned the value returned by the call to malloc, which represents the base address of the contiguous chunk of NxM int storage locations in the heap memory.
🌐
Reddit
reddit.com › r/c_programming › "correct" way of doing dynamically allocated multidimensional arrays in c
r/C_Programming on Reddit: "Correct" way of doing dynamically allocated multidimensional arrays in C
January 2, 2022 -

There are 3 ways that I know of to dynamically allocate a multidimensional array in C:

1- The malloc -> malloc -> malloc... way

int x = 4, y = 5;
int** arr = malloc(sizeof(*arr) * x);
for (int i = 0; i < x; ++i) {
    arr[i] = malloc(sizeof(arr[0]) * y);
}

This seems to be the worst method of them all. It's verbose to create and free and generates fragmented memory blocks. Also gets progressively bigger the more dimensions there are.

2- The 1D array with indexing way

int index(int x, int y, int maxX)
{
    return y * maxX + x;
}

int main(void)
{
    int x = 4, y = 5;
    int* arr = malloc(sizeof(*arr) * x * y);
    // get element at position (0, 2)
    int elem = arr[index(0, 2, x)];
}

This is better but not much. Having to call index every time you access the array is a pain. You would also need to create a index function for each number of dimensions.

2.1- The indexing way with a macro

#define ARR(X, Y) arr[Y * x + X]

int main(void)
{
    int x = 4, y = 5;
    int* arr = malloc(sizeof(*arr) * x * y);
    // get element at position (0, 2)
    int elem = ARR(0, 2);
}

I guess you could consider this better, but I personally don't really like it. Also has the same problems that number 2 has.

3- The VLA way

int x = 4, y = 5, z = 10, w = 2;
int (*arr2D)[y] = malloc(sizeof(int[x][y]));
int (*arr3D)[y][z] = malloc(sizeof(int[x][y][z]));
int (*arr4D)[y][z][w] = malloc(sizeof(int[x][y][z][w]));

This really looks like the perfect solution. Easy to adapt to any number of dimensions and easy to index. The only downside I could find is that VLA support is not required since C11, but I'm not sure if any big compiler doesn't support them.

So, is number 3 really the best way of doing it by a far margin? Or are there any downsides to it that I don't know of? What is the method you would use on some real world project?

🌐
Learningc
learningc.org › chapters › chapter09-multi-dimensional-arrays › 2d-dynamic-memory-alloc
9.3. Dynamic Memory Allocation of 2D Arrays — Snefru: Learning Programming with C
Third, we can access the elements as any 2D array. Forth, we free only the dynamically allocated three 1D arrays. #include <stdlib.h> int main(void) { // on Stack, statically have allocate 3 pointers, // each will point to a 1D array corresponding to a row int* arr[3]; // Access each pointer and make it point // to a newly dynamically allocated array for (int row = 0; row < 3; row++) { arr[row] = (int*)malloc(4 * sizeof(int)); } // Access elements as usual for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { arr[row][col] = row * 4 + col + 1; } } // Free only dynamically allocated space for (int row = 0; row < 3; row++) { free(arr[row]); } return 0; }
🌐
Eskimo
eskimo.com › ~scs › cclass › int › sx9b.html
23.2: Dynamically Allocating Multidimensional Arrays
#include <stdlib.h> int **array; ... NULL) { fprintf(stderr, "out of memory\n"); exit or return } } array is a pointer-to-pointer-to-int: at the first level, it points to a block of pointers, one for each row....
🌐
GeeksforGeeks
geeksforgeeks.org › c language › dynamically-allocate-2d-array-c
How to dynamically allocate a 2D array in C? - GeeksforGeeks
January 10, 2025 - #include <stdio.h> #include <stdlib.h> int main() { int r = 3, c = 4, len = 0; int *ptr, **arr; int count = 0, i, j; len = sizeof(int*) * r + sizeof(int) * c * r; arr = (int**)malloc(len); // ptr is now pointing to the first element of the 2D // array // it points to the memory just after the row pointers // allocated memory ptr = (int*)(arr + r); // for loop to point rows pointer to appropriate // location in 2D array for (i = 0; i < r; i++) arr[i] = (ptr + c * i); for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); return 0; } Output ·
🌐
Linux Hint
linuxhint.com › two-dimensional-array-malloc-c-programming
How to Create 2 Dimensional Array Using Malloc() in C Programming – Linux Hint
This will create problems, either the memory will become low for the array or the array will occupy less space wasting the memory so to avoid this, it is recommended to assign arrays dynamically. In C programming, for dynamic memory allocation, different functions are used. One of them is the malloc() function; it sends a request to the heap for a specific block of memory and if the heap has the space, it responds by allocating the requested block of memory to malloc().
🌐
Sololearn
sololearn.com › en › Discuss › 116505 › how-can-i-create-a-2d-dynamic-array-using-malloc-in-c
How can I create a 2D dynamic array using malloc() in C? | Sololearn: Learn to code for FREE!
arraysdynamiccmalloc · 3rd Dec 2016, 11:37 AM · Lorenzo Felletti · 3 Answers · Answer · + 2 · int **arr = (int **)malloc(row * sizeof(int *)); for (i=0; i<row; i++) arr[i] = (int *)malloc(column * sizeof(int)); for more details check out: http://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/ 4th Dec 2016, 3:20 AM ·
Find elsewhere
🌐
Quora
quora.com › How-do-you-allocate-memory-for-a-two-dimensional-array-using-malloc-in-C
How to allocate memory for a two-dimensional array using malloc() in C++ - Quora
`ElementType* array = malloc(width * height * sizeof(ElementType));` Remember that you have no overrun protection here. You may want to wrap this C style code in a C++ style class with inline accessors.
Top answer
1 of 5
4

You say in the comments that n is the number of rows. So you need to allocate n rows each of length m. Therefore, the second for loop condition should be i < n. Also, you should check the return value of malloc for NULL in case it fails to allocate memory. I suggest the following change -

long long **a = malloc(n * sizeof(*a));
for (i = 0; i < n; i++) {
    a[i] = malloc(m * sizeof(*a[i]));
}

Please note that a multi-dimensional array is not a fundamentally new type. It's simply an array of elements where each element itself is an array (for a 2D array), an array of arrays (for a 3D) array and so on. If you are using C99, you can allocate your array cleanly and succinctly as

int nrow = 4;  // number of rows
int ncol = 8;  // number of columns

// define arr to be a pointer to an array of ncol ints, i.e.,
// arr is a pointer to an object of type (int[ncol])
int (*arr)[ncol] = malloc(sizeof(int[nrow][ncol]));

// check the result of malloc for NULL
if (arr == NULL) {
    printf("malloc failed to allocate memory\n");
    // handle it
}

// do stuff with arr
for (int i = 0; i < nrow; i++) {
    for (int j = 0; j < ncol; j++) {
        arr[i][j] = i + j;
    }
}
// after you are done with arr
free(arr);

You should also go through this - How do I work with dynamic multi-dimensional arrays in C?

2 of 5
1

You have three errors: The first is that you allocate only 5 secondary arrays, but in the input you loop over 6 of them.

The second problem is that array indices are zero-based, i.e. the index start at zero and goes to the size minus one.

The third problem is that you scan for two numbers (why?), but you provide only one destination pointer to scanf.

🌐
GitHub
gist.github.com › 1196451
C 2D Array Malloc · GitHub
C 2D Array Malloc. GitHub Gist: instantly share code, notes, and snippets.
🌐
Blogger
pleasemakeanote.blogspot.com › 2008 › 06 › 2d-arrays-in-c-using-malloc.html
2D Arrays in C Using malloc
Pointers can be easily used to create a 2D array in C using malloc. The idea is to first create a one dimensional array of pointers, and then, for each array entry, create another one dimensional array.
🌐
Medium
medium.com › @pauljlucas › dynamically-allocating-2d-arrays-efficiently-and-correctly-in-c-1b35384e87bf
Dynamically Allocating 2D Arrays Efficiently (and Correctly!) in C | by Paul J. Lucas | Medium
November 3, 2025 - This all works fine for statically allocated 2D matrices where the dimensions are known at compile-time, but what if we don’t know the dimensions at compile-time? We then have to dynamically allocate it. But all C has is malloc() that simply allocates the given number of bytes.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Using malloc() and free() with 2D arrays in Arduino C - Programming - Arduino Forum
June 6, 2016 - I'm working on a project that involves ... as a 2D array of bytes. I noticed that after uploading a couple images it stopped working, which I'm fairly certain is because I'm simply running out of memory. I decided to do some research and experimentation, and started reading about malloc() and free() ...
🌐
Swarthmore College
cs.swarthmore.edu › ~newhall › unixhelp › C_arrays.html
Arrays in C
For a NxM 2D array: ... Allocate an array of arrays: allocate 1 array of N pointers to arrays, and allocate N M bucket array of values (on for each row). You could also allocate each column independently and have an array of column arrays. Depending on the method, the declaration and access ...
🌐
Nyu-cso
nyu-cso.github.io › notes › 07-structs_malloc_2d.pdf pdf
Strings, Structs, malloc, 2D arrays Jinyang Li
n = (node *)malloc(sizeof(node)); n-­‐>val = val; n-­‐>next = *headp; *headp = n; } int main() { node *head = NULL; for (long i = 10; i < 13; i++) { insert(&head, i); } } ..... 0x00..0c · 0x00...00 · Global · Heap · Stack · main.head: 0x00..0b · 0x00..00 · 0x00..0a · 2D Arrray · 2D arrays are stored con<guously in ·
🌐
Medium
medium.com › @MarkAiCode › dynamic-2d-array-allocation-in-c-2745e65d9828
Dynamic 2D Array Allocation in C. Memory management in C can be tricky… | by Mark Ai Code | Medium
October 27, 2024 - Before diving into 2D arrays, let’s quickly refresh the fundamentals of dynamic memory allocation: malloc(): Allocates a block of uninitialized memory
🌐
Ars OpenForum
arstechnica.com › forums › operating systems & software › programmer's symposium
2D array in C - Implimenting with malloc | Ars OpenForum
August 24, 2011 - T **arr = malloc(SIZE1 * sizeof *arr); // allocates a SIZE1-array of pointer to T. if (arr) { int i; for (i = 0; i < SIZE2; i++) { int j; arr[i] = malloc(SIZE2 * sizeof *arr[i]); // allocates a SIZE2-array of T. for (j = 0; j < SIZE2; j++) { arr[i][j] = some_initial_value(); } } } Pros: you ...