【问题标题】:How to create a 3D matrix in C by means of a function? [closed]如何通过函数在 C 中创建 3D 矩阵? [关闭]
【发布时间】:2015-08-13 12:25:17
【问题描述】:

我编写了以下 C 代码来在 3 维矩阵中创建和插入元素:

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;

}

createMatrix 函数中我插入然后检查存储在矩阵中的内容。 屏幕上的结果是:

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
...
...

我无法在 3D 矩阵中正确存储元素。 哪里错了?

【问题讨论】:

  • see why not to castmalloc()C中的family返回值。
  • scanf("%lf", &amp;matrix[i][j][j]); --> scanf("%lf", &amp;matrix[i][j][k]);
  • 对于细分的热爱please read this。它还包含执行您正在尝试的操作的正确代码。

标签: c matrix


【解决方案1】:

改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-17
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多