简体   繁体   中英

Unable to call a function from int main() body

This is the SUM function I've created, to handle the arbitrary number of integers.

#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

 [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. C++ however doesn't support such syntax. If you want to create an array to pass into sum , the simplest way would be like this

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.

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:

    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. You should take care of the overflow of your sum function's returned value also.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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