简体   繁体   English

无法从int main()主体中调用函数

[英]Unable to call a function from int main() body

This is the SUM function I've created, to handle the arbitrary number of integers. 这是我创建的SUM函数,用于处理任意数量的整数。

#include <iostream>
using namespace std;

int sum(const int numbers[], const int numbersLen){
    int sum = 0;
    for (int i=0; i < numbersLen; ++i){
        sum += numbers[i];
    }

    return sum;
}

I'm calling this function from the int main() but it keeps on giving the error 我正在从int main()调用此函数,但它不断给出错误

 [Error] invalid conversion from 'char' to 'const int*' [-fpermissive]

The main function is as below: 主要功能如下:

int main(){
    cout << sum([2],5);
    return 0;
}

I know the mistake is very naive and small but help will be highly appreciated! 我知道这个错误非常幼稚,但是非常感谢您的帮助!

You are trying to create an array literal via [2] , like some popular languages support. 您正在尝试通过[2]创建数组文字,例如一些流行的语言支持。 C++ however doesn't support such syntax. 但是C ++不支持这种语法。 If you want to create an array to pass into sum , the simplest way would be like this 如果要创建一个数组以传递给sum ,最简单的方法是这样的

int arr[] = {2};
cout << sum(arr,1);

Note I also adjusted the size you pass into the function, there is no bounds checking in C++, so to pass a size larger than your actual array is asking for trouble. 注意,我还调整了传递给函数的大小,C ++中没有边界检查,因此传递大于实际数组的大小会带来麻烦。

You need to send an array variable to the function as parameter. 您需要将数组变量作为参数发送给函数。 Try this.. 尝试这个..

int main(){
    int numbers[] = {1,2,3,4,5};
    cout << sum(numbers,5);
    return 0;
}

The error is from your function call: 错误来自您的函数调用:

    cout << sum([2], 5);

I think you want to pass the array with 5 values {2, 2, 2, 2, 2} to the sum function then it would be: 我认为您想将具有5个值{2,2,2,2,2}的数组传递给sum函数,那么它将是:

    int main() {
        int arr[] = {2, 2, 2, 2, 2};
        cout << sum(arr, 5);
        return 0;
    }

And one more thing in your sum function, it is totally fine to pass numbersLen as value so the const is removable. sum函数中还有一件事,将numbersLen作为值传递是完全可以的,因此const是可移动的。 You should take care of the overflow of your sum function's returned value also. 您还应该注意sum函数返回值的溢出。

The real problem lies in the arguments in your function call. 真正的问题在于函数调用中的参数。 The correct arguments are: 正确的参数是:

int main(){
       int array[] = {1,2,3,4,5}; 
       cout<<sum(array,5);
       return 0;
}

The below given code will solve your problem. 下面给出的代码将解决您的问题。

int main(){
int arr[] = {2};
cout << sum(arr,1);
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM