I am new to c language, and I have been trying to find an efficient and flexible way to define 2D matrices in c language. My goal is to create 2D matrices freely from anyplace in my program and being able to pass any number of matrices back to the main code. Below is my code and a figure that explains my understanding of this code. I tried my best to avoid ***pointers but I couldn't, please correct me if you think there is a better way to achieve this goal.
Matrix definition using a ***pointer.
#include<stdio.h>
#include<stdlib.h>
void createMatrix(int ***Mat, int N){
// Create N rows pointers
(*Mat) = malloc(N*sizeof(int *));
// For each row point, create N columns
for(int i=0; i<N; i++){
(*Mat)[i] = malloc(N*sizeof(int));
}
// Initialize matrix elements
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
(*Mat)[i][j] = 0;
}
}
};
void printMatrix(int ***Mat, int N){
// Print matrix elements
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
printf("%d ", (*Mat)[i][j]);
}
printf("\n");
}
};
void main(){
int N = 10;
// Allocate the pointers
int ***A;
A = malloc(sizeof(int *));
// Call the functions
createMatrix(A, N);
printMatrix(A, N);
free(A);
}