
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
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);
- Related Articles
- How to store a 2d Array in another 2d Array in java?
- How to convert a 2D array into 1D array in C#?
- How to pass a 2D array as a parameter in C?
- C++ Perform to a 2D FFT Inplace Given a Complex 2D Array
- How to create a dynamic 2D array inside a class in C++
- Passing a 2D array to a C++ function
- How to sort a 2D array in TypeScript?
- How to create a dynamic 2D array in Java?
- how to shuffle a 2D array in java correctly?
- How do I declare a 2d array in C++ using new
- How to declare Java array with array size dynamically?
- How to allocate memory in Javascript?
- Find a peak element in a 2D array in C++
- C# program to find K’th smallest element in a 2D array
- How to read a 2d array from a file in java?

Advertisements