How to dynamically allocate a 2D array in C?

Following are different ways to create a 2D array on heap (or dynamically allocate a 2D array).

In the following examples, we have considered ‘r‘ as number of rows, ‘c‘ as number of columns and we created a 2D array with r = 3, c = 4 and following values

1    2    3    4
5   6    7     8
9  10  11   12

Method 1 :- Using a single pointer

 

 

Method 2 :- Using an array of pointers

 

Method 3 :- Using pointer to a pointer

 

 

 

If you like this Article, then don’t forget to Click on Social likes buttons.