我有以下代码和方法:
- 创建矩阵
- 打印出来
- 将两个矩阵相加
#include <stdio.h>
#include <stdlib.h>
#define VECTOR_ROWS 3
#define VECTOR_COLS 1
void add_matrix(double***, double**, int, int);
void print_matrix(double**, int, int);
double** new_matrix(int, int);
int main() {
printf("First vector:n");
double **vector = new_matrix(VECTOR_ROWS, VECTOR_COLS);
print_matrix(vector, VECTOR_ROWS, VECTOR_COLS);
printf("nSecond vector:n");
double **vector2 = new_matrix(VECTOR_ROWS, VECTOR_COLS);
print_matrix(vector2, VECTOR_ROWS, VECTOR_COLS);
printf("nAdd vector:n");
add_matrix(&vector, vector2, VECTOR_ROWS, VECTOR_COLS);
print_matrix(vector, VECTOR_ROWS, VECTOR_COLS);
return 0;
}
void add_matrix(double*** matrix, double** trans_matrix, int rows, int cols)
{
int r, c;
for (r = 0; r < rows; r++)
for (c = 0; c < cols; c++)
*matrix[c][r] += trans_matrix[r][c]; // WHY DOES IT WORK THIS WAY?
}
double** new_matrix(int row, int col)
{
double **matrix = (double**)malloc(row * sizeof(double*));
int r, c;
for(r = 0; r < row; r++)
matrix[r] = (double*)malloc(col * sizeof(double));
for (r = 0; r < row; r++)
for (c = 0; c < col; c++)
scanf("%lf", &matrix[r][c]);
return matrix;
}
void print_matrix(double** matrix, int rowCount, int colCount)
{
int r, c;
for (r = 0; r < rowCount; r++)
{
for (c = 0; c < colCount; c++)
printf("%lf ", matrix[r][c]);
printf("n");
}
}
基本上,我创建vector和vector2并尝试添加它们。只有当add_matrix(…(中的第一个矩阵交换了[r][c]时,它才有效,就好像因为我通过引用传递了它,所以它的行和列交换了一样。如果我用[r][c]引用它,我会得到一个sef错误,但这很有效,我不知道为什么。
此分配中的左操作数
*matrix[c][r] += trans_matrix[r][c];
不正确。
那就是左边的操作数相当于
*( matrix[c][r] )
写入
( *matrix )[r][c] += trans_matrix[r][c];
或
matrix[0][r][c] += trans_matrix[r][c];
实际上,通过引用将指针传递到第一个矩阵是没有意义的,因为指针本身在函数中没有改变。
该函数可以像一样声明
void add_matrix(double** matrix, double** trans_matrix, int rows, int cols);