【发布时间】: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 cast
malloc()和C中的family返回值。 -
scanf("%lf", &matrix[i][j][j]);-->scanf("%lf", &matrix[i][j][k]); -
对于细分的热爱please read this。它还包含执行您正在尝试的操作的正确代码。