Dynamically allocate memory for a 3D array in C
This post will discuss various methods to dynamically allocate memory for 3D array in C using Single Pointer and Triple Pointer.
Related Post:
1. Using Single Pointer
In this approach, we simply allocate memory of size M×N×O
dynamically and assign it to a pointer. Even though the memory is linearly allocated, we can use pointer arithmetic to index the 3D array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
#include <stdio.h> #include <stdlib.h> // `M × N × O` matrix #define M 2 #define N 3 #define O 4 // Dynamically allocate memory for 3D Array int main() { // dynamically allocate memory of size `M × N × O` int* A = (int*)malloc(M * N * O * sizeof(int)); if (A == NULL) { fprintf(stderr, "Out of memory"); exit(0); } // assign values to the allocated memory for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < O; k++) { *(A + i*N*O + j*O + k) = rand() % 100; } } } // print the 3D array for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < O; k++) { printf("%d ", *(A + i*N*O + j*O + k)); } printf("\n"); } printf("\n"); } // deallocate memory free(A); return 0; } |
2. Using Triple Pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
#include <stdio.h> #include <stdlib.h> // `M × N × O` matrix #define M 2 #define N 3 #define O 4 // Dynamically allocate memory for 3D Array int main() { int*** A = (int***)malloc(M * sizeof(int**)); if (A == NULL) { fprintf(stderr, "Out of memory"); exit(0); } for (int i = 0; i < M; i++) { A[i] = (int**)malloc(N * sizeof(int*)); if (A[i] == NULL) { fprintf(stderr, "Out of memory"); exit(0); } for (int j = 0; j < N; j++) { A[i][j] = (int*)malloc(O * sizeof(int)); if (A[i][j] == NULL) { fprintf(stderr, "Out of memory"); exit(0); } } } // assign values to the allocated memory for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < O; k++) { A[i][j][k] = rand() % 100; } } } // print the 3D array for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < O; k++) { printf("%d ", A[i][j][k]); } printf("\n"); } printf("\n"); } // deallocate memory for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { free(A[i][j]); } free(A[i]); } free(A); return 0; } |
That’s all about dynamically allocating memory for a 3D array in C.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)