通过引用传递时,动态数组交换列和行

问题描述

我有以下代码,其中包含以下方法

  1. 创建矩阵
  2. 打印
  3. 添加两个矩阵
#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);
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_COLS);
    
    printf("\nAdd vector:\n");
    add_matrix(&vector,vector2,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]引用它,则会遇到严重错误,但这是可行的,我也不知道为什么。

解决方法

此分配中的左操作数

*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);