I wrote the following C code to create and insert elements in a 3 dimensional matrix:
double*** createMatrix(int n_rows, int n_cols, int depth) {
double ***matrix;
matrix = (double***)malloc(n_rows*sizeof(double**));
for (int row = 0; row < n_rows; row++) {
matrix[row] = (double**)malloc(n_cols*sizeof(double*));
for (int col = 0; col < n_cols; col++) {
matrix[row][col] = (double*)malloc(depth*sizeof(double));
}
}
printf("Insert the elements of your matrix:\n");
for (int i = 0; i < n_rows; i++) {
for (int j = 0; j < n_cols; j++) {
for (int k = 0; k < depth; k++) {
printf("Insert element [d][d][%d]: ", i, j, k);
scanf("%lf", &matrix[i][j][j]);
printf("matrix[%d][%d][%d]: %lf\n", i, j, k, matrix[i][j][k]);
}
}
}
return matrix;
}
int main() {
double ***matrix;
matrix = createMatrix(3, 3, 3);
return 0;
}
In the createMatrix
function I insert and then check what is stored in the matrix.
The result on the screen is:
Insert the elements of your matrix:
Insert element [0][0][0]: 1
matrix[0][0][0]: 1.000000
Insert element [0][0][1]: 2
matrix[0][0][1]: 0.000000
Insert element [0][0][2]: 3
matrix[0][0][2]: 0.000000
Insert element [0][1][0]: 4
matrix[0][1][0]: 0.000000
...
...
I am not able to correctly store elements in a 3D matrix. Where is the mistake?