joe souaid
joe souaid

Reputation: 40

C : function that calculates the sum of an array using pointers

the purpose is to return the sum of *a into *sum but I am not very good with pointers, I believe there should be a & somewhere

int sumArray (int * a, int len , int * sum ){
    if (a==NULL || sum==NULL ) return -1;
      int i;
      for (i=0;i<len;i++){
          sum[i]+=a[i];
      }
      return 0;
}

Upvotes: 0

Views: 675

Answers (1)

Hayfa
Hayfa

Reputation: 147

From what I understand from your comment, the parameter sum is not an array, but rather the variable where the sum will be stored. And since sum is a pointer, to store values into it, you must access its value this way : (*sum)

int sumArray (int * a, int len , int * sum ){
    if (a==NULL || sum==NULL ) return -1;
      int i;
      (*sum) = 0 ;
      for (i=0;i<len;i++){
         (*sum) += a[i];
      }
      return 0;
}

Upvotes: 2

Related Questions