How to Dynamically Allocate 2D Array in C: Syntax and Example
To dynamically allocate a 2D array in C, use
malloc to allocate memory for an array of pointers, then allocate memory for each row separately. This creates a flexible 2D array where size can be set at runtime.Syntax
To create a dynamic 2D array, first allocate memory for an array of pointers (each pointer will point to a row). Then allocate memory for each row separately.
int **array = malloc(rows * sizeof(int *));allocates memory for row pointers.array[i] = malloc(cols * sizeof(int));allocates memory for each row.
c
int **array = malloc(rows * sizeof(int *)); for (int i = 0; i < rows; i++) { array[i] = malloc(cols * sizeof(int)); }
Example
This example shows how to allocate a 3x4 2D array dynamically, fill it with values, print them, and then free the memory.
c
#include <stdio.h> #include <stdlib.h> int main() { int rows = 3, cols = 4; int **array = malloc(rows * sizeof(int *)); if (array == NULL) { printf("Memory allocation failed\n"); return 1; } for (int i = 0; i < rows; i++) { array[i] = malloc(cols * sizeof(int)); if (array[i] == NULL) { printf("Memory allocation failed\n"); // Free previously allocated rows for (int j = 0; j < i; j++) { free(array[j]); } free(array); return 1; } } // Fill the array for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { array[i][j] = i * cols + j + 1; } } // Print the array for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", array[i][j]); } printf("\n"); } // Free the memory for (int i = 0; i < rows; i++) { free(array[i]); } free(array); return 0; }
Output
1 2 3 4
5 6 7 8
9 10 11 12
Common Pitfalls
Common mistakes when dynamically allocating 2D arrays include:
- Not checking if
mallocreturnsNULL, which means allocation failed. - Forgetting to free all allocated memory, causing memory leaks.
- Allocating memory incorrectly, such as using
sizeof(int)instead ofsizeof(int *)for the array of pointers. - Accessing out-of-bounds indices, which leads to undefined behavior.
c
// Wrong: Allocating only one block without pointers int *array = malloc(rows * cols * sizeof(int)); // Accessing as array[i][j] will not work // Right: Allocate array of pointers, then each row int **array = malloc(rows * sizeof(int *)); for (int i = 0; i < rows; i++) { array[i] = malloc(cols * sizeof(int)); }
Quick Reference
Tips for dynamic 2D arrays in C:
- Always check if
mallocreturnsNULL. - Free memory in reverse order: free each row, then the array of pointers.
- Use nested loops to access elements:
array[i][j]. - Remember that rows can have different lengths if needed (jagged arrays).
Key Takeaways
Use malloc twice: once for row pointers, once for each row's columns.
Always check malloc's return value to avoid crashes.
Free all allocated memory to prevent leaks.
Access elements with array[i][j] after allocation.
Dynamic 2D arrays allow flexible sizes set at runtime.