1

I am trying to pass a 2D array of variable size to a function to print it.but the code doesn't show the exact result of sum.

this is the code:

#include <stdio.h>

#define ROW 5
#define COLL 5

void print_arr(int a[][COLL],int m,int n){
int i,j,sum;
for(i=0;i<m;i++){
  for(j=0;j<n;j++){
         printf("a[%d][%d]=%d\n",i,j,a[i][j]);
     }
   }
}

int sum_arr(int a[][COLL],int m,int n){
int i,j,sum;

for(i=0;i<m;i++){
    for(j=0;j<n;j++){
        sum+=a[i][j];
    }
  }
  return sum;
}

int main (void){
int a[ROW][COLL];
int i,j,m,n;
int sum;

printf("enter rows:");scanf("%d",&m);
printf("enter coll:");scanf("%d",&n);

for(i=0;i<m;i++){
    for(j=0;j<n;j++){
        printf("a[%d][%d]=",i,j);scanf("%d",&a[i][j]);
    }
}
print_arr(a,m,n);
printf("\n");

   sum=sum_arr(a,m,n);
   printf("sum=%d\n",sum);
   return 0;
}

this is the result of the code

enter rows:2
enter coll:3
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6

sum=-1217388517

please tell me what's wrong with the code....

2
  • Try initializing sum=0 Commented Feb 28, 2014 at 21:17
  • pointer_multi_array.c:15:21: error: ‘n’ undeclared here (not in a function) pointer_multi_array.c: In function ‘main’: pointer_multi_array.c:42:2: error: type of formal parameter 1 is incomplete i got the above error when i change yhe size of array to n Commented Feb 28, 2014 at 21:17

3 Answers 3

1

You should pass the exact size of the second dimension of the array to the function, not COLL. change it to m (or n, whatever) It passes the number 5 to the function while the number should be 3 :) How ever, this is not the main reason that you're code is not working, just a suggestion. Initialize the variable sum. It will make your code work. e.g. sum = 0; If you don't initialize it, you won't get any compile errors, but it points to a location of memory and reads thing been there before (not a valid amount) and uses it as the initial amount of that for sum. So your array is being added to a non-valid amount, that's why your code doesn't work.

Sign up to request clarification or add additional context in comments.

Comments

1

There is no technical problem with passing, but in sum_arr,
your variable sum does not start at 0 (but some strange value).

Comments

1

You have to initialize sum to zero in sum_arr function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.