2016-10-02 62 views
-2

我是非常新的在C 我试图做一小块代码,用户可以输入5个整数。 它们被添加到一个数组中,并且数组传入一个函数以汇总其所有元素。但是我收到了一些我不太明白的错误。在函数中传递数组以总结其元素

这是一段代码:

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

这是我得到的错误,当我编译: 我不明白为什么我得到“的‘sumArr’静态声明如下非静态声明“,即使在声明什么数据类型成立之后。

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[]); 
    ^
+0

首先,您可能希望将定义'sumArr()'*移出* main()的范围。 – alk

+0

你的大括号混淆了'main'。 – Dan

回答

1

您的函数中没有第二个参数。你应该这样做:

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

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

'',size_t s)''和'sumArr()'里面使用'size_t i;'而不是'int i;''。 – alk

0

你应该这样做。

int sumArr(int arr [],int size);

您传递5作为第二个参数。

1

test3.c:22:2: error: too many arguments to function ‘sumArr’

这几乎告诉你什么是问题。 sumArr被定义为

int sumArr(int arr[]) 
{ 
... 
} 

然而,你正在试图用两个参数来调用它:数组和整数5.为了解决这个问题,更改上面

int sumArr(int arr[], int variableName) 
{ 
... 
} 

test3.c:31:6: error: static declaration of ‘sumArr’ follows non-static declaration

两个功能sumArr()的功能原型(单行int sumArr(int arr[]);需要更改以符合上述更改)和定义(实际提供功能代码的位置)目前位于main()的内部。把它们移到外面,把原型以上main()功能。