【发布时间】:2020-12-14 15:50:47
【问题描述】:
我已经想出了如何使这个工作,但无法在这里详细解释这两个代码有什么不同。
不正确的代码:
const int nRows = 2;
const int nCols = 2;
int * colSum (int [nRows][nCols]);
int * rowSum (int [nRows][nRows]);
int main() {
int my2Darray[nRows][nCols] = {{10, 20}, {30, 40}};
int totalsByColumn[nCols] = {};
*totalsByColumn = *(colSum(my2Darray));
for (int i = 0; i < nCols; i++) {
cout << totalsByColumn[i] << endl;
}
}
int * colSum (int arrayArg[nRows][nCols]) {
static int arr[nRows] = {};
for (int i = 0; i < nCols; i++) {
for (int rowcount = 0; rowcount < nRows; rowcount++) {
arr[i] += arrayArg[rowcount][i];
}
}
return arr;
}
我得到 40 0 作为输出。
然后我通过这样做来修复它:
int main() {
int my2Darray[nRows][nCols] = {{10, 20}, {30, 40}};
int *totalsByColumn = colSum(my2Darray);
for (int i = 0; i < nCols; i++) {
cout << totalsByColumn[i] << endl;
}
}
输出是 40 60,正是我想要的。
我是否只是通过在我的第一个代码块上使用取消引用运算符而衰减到 totalsByColumn 的第一个元素?我觉得可能有一种更快的方法可以将列和行添加在一起并将它们分配给主函数中的数组,但只要它符合我的要求,我暂时就可以了。
【问题讨论】:
-
解引用运算符解引用一个
int -
*totalsByColumn = *(colSum(my2Darray))等价于totalsByColumn[0] = colSum(my2Darray)[0]。您只分配totalsByColumn的一个元素,另一个保留它之前的任何值。 -
我不知道你为什么用原始数组让你的生活变得困难,使用
std::vector。 -
@Quimby 或
std::array,如果每个数组的维度是编译时常量,就像这里一样。在函数之间传递数组既繁琐又烦人,标准库容器要好得多。 -
@Quimby 新手喜欢指点。这是生活中的事实(或糟糕的教学)。