-2

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?

MC93
  • 791
  • 6
  • 14
Saverio
  • 249
  • 3
  • 4
  • 10
  • 3
    Please [see why not to cast](http://stackoverflow.com/q/605845/2173917) the return value of `malloc()` and family in `C`. – Sourav Ghosh Aug 13 '15 at 12:28
  • 4
    `scanf("%lf", &matrix[i][j][j]);` --> `scanf("%lf", &matrix[i][j][k]);` – Spikatrix Aug 13 '15 at 12:29
  • For the love of segmentation [please read this](http://stackoverflow.com/questions/28317035/double-free-or-corruption-3d-array-in-c/28318050#28318050). It also contains correct code for doing what you are attempting. – Lundin Aug 13 '15 at 13:00

1 Answers1

2

change the

scanf("%lf", &matrix[i][j][j]);

to

scanf("%lf", &matrix[i][j][k]);
BeyelerStudios
  • 4,243
  • 19
  • 38