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;
}

-----------------------------------------------------------------------------------

The output reads:

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!