无法通过引用正确传递数组
Unable to pass array by reference correctly
我正在尝试将数组的两行添加到一个函数中,但它没有这样做,我无法说出为什么它不是,因为代码看起来正确并且没有出错。 我尝试使用 * 和 & 通过引用传递它,但我总是收到代码错误。 谢谢
#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 个整数的数组。
相关文章:
- 通过指针与数组引用扩展数组索引序列
- 将链表的内容放在数组引用中
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- C 在将数组引用分配给struct时麻烦
- Typedef数组引用
- 通过强制转换创建子数组引用
- 将数组引用 'T(&)[n]' 引用到 'std::array<T, n>' 的内容
- constexpr 数组引用参数
- 寻找有关函数定义和原型中数组引用的说明
- Initializer_list作为非模板上下文中数组引用参数的参数
- 如何使用一个动态创建的一维数组的二维数组引用仅与标准库?
- 如何返回具有大小的POD数组引用
- 在C++中返回数组引用的语法
- 是否可以声明转换函数返回数组引用而不使用typedef
- 自定义到数组引用的转换
- 类数组引用的NullReferenceException
- 数组指针与数组引用之间的差异
- 在c++中传递数组引用
- 使用特征矩阵作为特征数组引用的参数
- 如何从函数传递数组引用