How to dynamically allocate a 2D array in C?



A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.

A program that demonstrates this is given as follows.

Example

Live Demo

 #include <stdio.h> #include <stdlib.h> int main() { int row = 2, col = 3; int *arr = (int *)malloc(row * col * sizeof(int)); int i, j; for (i = 0; i < row; i++) for (j = 0; j < col; j++) *(arr + i*col + j) = i + j; printf("The matrix elements are:
"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { printf("%d ", *(arr + i*col + j)); } printf("
"); } free(arr); return 0; }

The output of the above program is as follows.

 The matrix elements are: 0 1 2 1 2 3 

Now let us understand the above program.

The 2-D array arr is dynamically allocated using malloc. Then the 2-D array is initialized using a nested for loop and pointer arithmetic. The code snippet that shows this is as follows.

 int row = 2, col = 3; int *arr = (int *)malloc(row * col * sizeof(int)); int i, j; for (i = 0; i < row; i++) for (j = 0; j < col; j++) *(arr + i*col + j) = i + j; 

Then the values of the 2-D array are displayed. Finally the dynamically allocated memory is freed using free. The code snippet that shows this is as follows.

 printf("The matrix elements are:
"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { printf("%d ", *(arr + i*col + j)); } printf("
"); } free(arr);
Updated on: 2019-07-30T22:30:23+05:30

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements