Home > front end >  How to print the sum of a passing a int array as a parameter
How to print the sum of a passing a int array as a parameter

Time:11-25

#include <stdio.h>
int sumofArrayNum(int numList[]);

int main(){
int result,numList[]={23,32,54,23,54,32,3,35};

result = sumofArrayNum(numList);
printf("sum= %d", result);
return 0;
}

int sumofArrayNum(int numList[]){
 int sum = 0;

  for(int i = 0; i < 10;   i){
   sum  = numList[i];
  }
  return sum;
}

Output is different each time I build and run it. E.g. output is sum = 1032918821

Expected output I would like is sum = 256

CodePudding user response:

In numlist there are 8 element that means for loop must execute code 8 times. Your code must be:

for(int i = 0; i < 8;   i)
{
   sum  = numList[i];
}

This code iterate until i=7, when i=8 it will end the loop.

Information on for loop

CodePudding user response:

Parameters like int numList[] is the same as int* numList, compiler will not know elements count of it if it was not explicitly defined. By the way, int numList[8] is also the same as int* numList. C language does not check the range of array.

There are some ways to get and check the array size.

  • size/count parameter
int sumofArrayNum(int numList[], int listSize){
 int sum = 0;
  for(int i = 0; i < listSize;   i){
   sum  = numList[i];
  }
  return sum;
}

Here listSize should be the count of elements.

And you can use macro to hide the count parameter:

#define sumofArray(array) sumofArrayNum((array), sizeof(array)/sizeof(*array))
  • point to the whole array
int sumofArrayNum(int (*numList)[8]){
 int sum = 0;
  for(int i = 0; i < sizeof(*numList)/sizeof(**numList);   i){
   sum  = (*numList)[i];
  }
  return sum;
}

Call it by sending pointer of array:

result = sumofArrayNum(&numList);

Compiler(such as gcc) can do a weak check for this: give a warning if you send an array which are not int (*)[8].

Note that you have to ensure validity of array, and array size must be constant.


Besides,

Output is different each time I build and run it.

It is because only 8 elements has been defined, index range is 0〜7. numList[8] and numList[9] is undefined, mean any value is possible. Maybe used, changed by other process, random and dangerous.

  • Related