无法通过引用正确传递数组

Unable to pass array by reference correctly

本文关键字:数组 引用      更新时间:2023-10-16

我正在尝试将数组的两行添加到一个函数中,但它没有这样做,我无法说出为什么它不是,因为代码看起来正确并且没有出错。 我尝试使用 * 和 & 通过引用传递它,但我总是收到代码错误。 谢谢

#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
void addRow(int arr[100][100], int firstrow,int secondrow,int rows, int cols);
void addRow(int arr[100][100], int firstrow,int secondrow,int rows, int cols){
    int i =0;
    int j = cols;
    while(i<rows){
        arr[secondrow][j]+=arr[firstrow][j];
        i++;
        j++;
    }
    print(arr,rows,cols);
}

数组传递正确,是你的代码没有正确执行添加。

您将j设置为开头的cols,并按递增顺序移动它,并带有j++ 。因此,您对数组元素的所有访问都超过了行的末尾。循环退出条件也不对,除非矩阵始终是平方的(在这种情况下,没有必要为行和列传递单独的计数)。

这应该有效:

void addRow(int arr[100][100], int firstrow,int secondrow,int rows, int cols){
    for(int j = 0 ; j != cols ; j++){
        arr[secondrow][j] += arr[firstrow][j];
    }
    print(arr, rows, cols);
}
void addRow(int (&arr)[100][100], int firstrow,int secondrow,int rows, int cols);

如果要通过引用传递,将是正确的签名。

template <typename std::size_t rows, std::size_t cols>
void addRow(int (&arr)[rows][cols], int firstrow,int secondrow);

那么你甚至不需要行和列作为程序上下文中的参数。

arr[100][100]更改为arr[][100] 。 (实际上,其他一些更改,例如使 100 成为符号常量,将有助于改进代码的样式,但这是需要更改的主要内容。

原因并非易事,但对于C++编程仍然很重要。 实际上传递给函数addRow()的是 - 请仔细阅读以下内容 - 第一行 100 个整数的地址。 这个地址反过来是第一个整数的地址,但传递语义是我说的。 因此,在addRow()内,符号arr充当指向 100 个整数数组的常量指针,而不是指向 10,000 个整数的数组。