I figured out how to make this one work already but can't explain in details what is so different in these two codes here.
Incorrect code:
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;
}
I was getting 40 0 as the output.
Then I fixed it by doing this:
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;
}
}
Output is 40 60, just what I wanted.
Was I just decaying to the first element of totalsByColumn by using the dereference operator on my first block of code? I feel like there might be a quicker way of adding the columns and rows together and assigning them to arrays in the main function, but as long as it does what I want I'm okay with that for the moment.
int*totalsByColumn = *(colSum(my2Darray))is equivalent tototalsByColumn[0] = colSum(my2Darray)[0]. You are only assigning one element oftotalsByColumn, the other preserves whatever value it had previously.std::vector.std::arrayif the dimension of each array is a compile-time constant as it is here. Passing arrays to and from functions is fiddly and annoying, the standard library containers are a lot nicer.