function for 2d dynamic array
#include <stdio.h>
#include <stdlib.h>
int createDynamicArray(int rows, int columns) {
int array = (int)malloc(rows sizeof(int));
for (int i = 0; i < rows; i++) {
array[i] = (int)malloc(columns sizeof(int));
}
return array;
}
void freeDynamicArray(int array, int rows) {
for (int i = 0; i < rows; i++) {
free(array[i]);
}
free(array);
}
int main() {
int rows = 3;
int columns = 4;
int array = createDynamicArray(rows, columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = i + j;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
freeDynamicArray(array, rows);
return 0;
}
Explanation:
- The createDynamicArray
function takes two parameters: rows
and columns
. It dynamically allocates memory for a 2D array using malloc
.
- It first allocates memory for an array of rows
pointers using malloc(rows sizeof(int))
.
- Then, it iterates over each row and allocates memory for an array of columns
integers using malloc(columns * sizeof(int))
.
- The function returns the dynamically created 2D array.
- The freeDynamicArray
function is used to free the dynamically allocated memory. It takes two parameters: array
and rows
.
- It iterates over each row and frees the memory allocated for that row using free(array[i])
.
- Finally, it frees the memory allocated for the array of pointers using free(array)
.
- In the main
function, we create a 2D array with 3 rows and 4 columns using the createDynamicArray
function.
- We then populate the array with some values.
- After that, we print the array.
- Finally, we free the dynamically allocated memory using the freeDynamicArray
function.