2d array c dynamic code example
Example: how to pass a dynamic 2d array to a function c
#include <stdio.h>
#include <stdlib.h>
void assign(int** arr, int m, int n)
{
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = i + j;
}
}
}
int main(void)
{
int m = 5;
int n = 5;
int **arr = (int **)malloc(m * sizeof(int *));
for (int r = 0; r < m; r++)
arr[r] = (int *)malloc(n * sizeof(int));
assign(arr, m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%3d", arr[i][j]);
}
printf("\n");
}
for (int i = 0; i < m; i++)
free(arr[i]);
free(arr);
return 0;
}