- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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);
Advertisements