#include <stdio.h>
#include <stdlib.h>
// Dynamically allocated 2D array (array of pointers)
// A callback function applied to each element
/* -------------------- Allocation -------------------- */
int **allocate2D(int rows, int cols) {
int **arr = malloc(rows * sizeof(int*));
if (!arr) {
perror("malloc failed");
exit(1);
}
for (int r = 0; r < rows; r++) {
arr[r] = malloc(cols * sizeof(int));
if (!arr[r]) {
perror("malloc failed");
exit(1);
}
}
return arr;
}
/* -------------------- Fill -------------------- */
void fill2D(int rows, int cols, int **arr, int startValue) {
int v = startValue;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
arr[r][c] = v++;
}
/* -------------------- Print -------------------- */
void print2D(int rows, int cols, int **arr) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++)
printf("%d ", arr[r][c]);
printf("\n");
}
}
/* -------------------- Free -------------------- */
void free2D(int rows, int **arr) {
for (int r = 0; r < rows; r++)
free(arr[r]);
free(arr);
}
/* -------------------- Callback Application -------------------- */
void apply2D(int rows, int cols, int **arr, void (*cb)(int*)) {
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
cb(&arr[r][c]);
}
/* callback function */
void increment(int *x) {
(*x)++;
}
/* -------------------- Main -------------------- */
int main() {
int rows = 3, cols = 4;
int **arr = allocate2D(rows, cols);
fill2D(rows, cols, arr, 1);
printf("Before callback:\n");
print2D(rows, cols, arr);
apply2D(rows, cols, arr, increment);
printf("\nAfter callback:\n");
print2D(rows, cols, arr);
free2D(rows, arr);
return 0;
}
/*
run:
Before callback:
1 2 3 4
5 6 7 8
9 10 11 12
After callback:
2 3 4 5
6 7 8 9
10 11 12 13
*/