C++ 返回函数';将静态数组转换为main()函数中的另一个数组
我已经知道了如何使这一个工作,但不能详细解释这两个代码有什么不同 错误代码:C++ 返回函数';将静态数组转换为main()函数中的另一个数组,c++,arrays,function,C++,Arrays,Function,我已经知道了如何使这一个工作,但不能详细解释这两个代码有什么不同 错误代码: 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
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;
}
const int nRows=2;
常数int nCols=2;
int*colSum(int[nRows][nCols]);
整数*行和(整数[nRows][nRows]);
int main(){
int my2Darray[nRows][nCols]={{10,20},{30,40};
int totalsByColumn[nCols]={};
*totalsByColumn=*(colSum(my2Darray));
对于(int i=0;i
对
我觉得可能有一种更快的方法将列和行添加到一起
当然可以。与您的解决方案不同,还有一些线程安全的方法。一种简单的方法是使用输出迭代器直接写入您想要结果的数组:
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);
int*colSum(int-arrayArg[][nCols],int-out[]{
对于(int i=0;i
取消引用运算符取消引用一个int
*totalsByColumn=*(colSum(my2Darray))
相当于totalsByColumn[0]=colSum(my2Darray)[0]
。您只分配了totalsByColumn
的一个元素,另一个元素保留了它以前的任何值。我不知道为什么使用原始数组会让您的生活变得困难,如果每个数组的维数都是编译时常量,请使用std::vector
@Quimby或std::array
。传递arrays往返函数既烦琐又烦人,标准的库容器要好得多。@Quimby新手喜欢指针。这是生活中的事实(或糟糕的教学)。非常感谢,这样更好!
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);