【问题标题】:Returning a function's static array to another array in the main() function在 main() 函数中将函数的静态数组返回到另一个数组
【发布时间】: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 新手喜欢指点。这是生活中的事实(或糟糕的教学)。

标签: c++ arrays function


【解决方案1】:

我是否只是通过在我的第一个代码块上使用取消引用运算符而衰减到 totalsByColumn 的第一个元素?

是的。

我觉得可能有一种更快的方法将列和行添加在一起

当然。还有与您的解决方案不同的线程安全方式。一种简单的方法是使用输出迭代器直接写入您想要结果的数组:

int* colSum (int arrayArg[][nCols], int out[]) {
    for (int i = 0; i < nCols; i++) {
        out[i] = 0;
        for (int rowcount = 0; rowcount < nRows; rowcount++) {
            out[i] += arrayArg[rowcount][i];
    // ...

int totalsByColumn[nCols];
colSum(my2Darray, totalsByColumn);

【讨论】:

  • 非常感谢,这样好多了!
猜你喜欢
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 2020-07-20
相关资源
最近更新 更多