# Thread: calculate column-wise sum of a matrix in C

1. ## calculate column-wise sum of a matrix in C

Hi All,

I am new to C programming. I was trying to do column-wise sum of a matrix whose elements are integers. This is very easy to do in R (by calling the 'colSums' function). However, my c code below does not yield right output. I would appreciate if anyone can help.

Code:
```#include <stdio.h>
#define n_sample 4
int *colSums_IntMat(int IntMat_In[][n_sample],int nrow){
int i,j,array[n_sample];
int *ptr;
for (j=0;j<n_sample; j++) {
array[j]=0;
for (i=0; i<nrow; i++) {
array[j]=array[j]+IntMat_In[i][j];
}
}
ptr=array;
return ptr;
}

int main (int argc, const char * argv[]) {
int mat[4][n_sample]={{1,0,1,0},
{0,0,1,1},
{0,1,0,0},
{1,0,0,0}};
int *colsum,i;
colsum=colSums_IntMat(mat,4);
for (i=0; i<n_sample; i++) {
printf("Column sum for %d column is %d.\n",i,*(colsum++));
}
return 0;
}```
-----------------------------------------------------------------------------------
Column sum for 0 column is 2.
Column sum for 1 column is 0.
Column sum for 2 column is 0.
Column sum for 3 column is 0.
which is not correct. The correct output should be:
Column sum for 0 column is 2.
Column sum for 1 column is 1.
Column sum for 2 column is 2.
Column sum for 3 column is 1.

Can anyone help? Thanks a lot.

On another note, can we calculate column-wise sum of an arbitrary 2-d array with unknown row and column numbers? Thanks again!

2. Your array (in colSums_IntMat) is a local variable, and you're returning a pointer to it.
The problem is the array goes out of scope when the function returns, and your pointer is then invalid (anything can happen).

Declare an actual array in main, and pass that array as another parameter, and store the results in that parameter.

3. Thanks. I will try to modify that and see if it works. I will update my thread then.

4. I tried to follow Salem, still got the same output. Totally confused now!

5. Well so are we - we can't see your latest code.