Titus-Waffle-Master Titus-Waffle-Master - 2 months ago 9
C Question

Passing array in function to sum its elements

I am very new at C.
I'm trying to do a little piece of code where the user gets to enter 5 integers.
They get added in an array and the array passed in a function to sum all its elements. But i'm getting a bunch of errors back that I don't quite understand.

this is the piece of code:

#include <stdio.h>

void main()
{
int array[5];
int index;
int sum;
//Function declaration.
int sumArr(int arr[]);


for (index = 0; index <= 4; index++)
{
printf("Please enter an integer: ");
scanf("%d", &array[index]);
}

sum = sumArr(array, 5);

printf("The total sum of the integers contained in the array is: %d", sum);


//Function to summ the values sored in the array.

int sumArr(int arr[])
{
int i;
int sum = 0;

for (i = 0; i < 4; ++i)
{
sum += arr[i];
}
return sum;
}
}


And this is the errors I get when I compile:
I don't understand why I get "static declaration of ‘sumArr’ follows non-static declaration", even after declaring what datatype holds.

test3.c: In function ‘main’:
test3.c:22:2: error: too many arguments to function ‘sumArr’
sum = sumArr(array, 5);
^
test3.c:12:5: note: declared here
int sumArr(int arr[]);
^
test3.c:31:6: error: static declaration of ‘sumArr’ follows non-static declaration
int sumArr(int arr[])
^
test3.c:12:5: note: previous declaration of ‘sumArr’ was here
int sumArr(int arr[]);
^

Answer

You haven't the second argument in your function. You should do this:

int sumArr(int arr[], int s)
{
    int i;
    int sum = 0;

    for (i = 0; i < s; ++i)
    {
        sum += arr[i];
    }
    return sum;
}