I am getting errors while trying to return an array in C++

First of all, the errors are pretty self explanatory.

invalid conversion from int* to int

Your function is declared in such a way it is expected to return an int. Not an array of ints, just an int. Furthermore, you cannot return an array from a function. You can, however, return a pointer to the first element, which in your case is unnecessary.

Guessing that you want your function to simply set values in an array, you can achieve that by declaring the function as void returning:

void power(int x[5])
{
    x[0]=12;
    x[1]=23;
    x[2]=234;
    x[3]=344;
    x[4]=232;
}

x was not declared in this scope

Well, given your main:

int main()
{
    int action[5]={1,2,3,,4,5};
    std::cout<<x[0]<<std::endl;
    //         ^
    ...
}

Here you attempt to use a variable x, which was never declared inside main or as global variable, thus the compiler has no idea what you are referring to. Simply aliasing an argument as x in some unrelated function won’t make it visible to all the code. Your can’t use it like this.

expected primary expression before’,’ token

Take a close look at your main function and at action declaration. The part:

int action[5]={1,2,3,,4,5};
//                  ^^

is illegal. Notice the ,,. You either should put an integer inbetween them, or delete one of them.

What you probably wanted to achieve, was to first declare the array, print out the first element, apply the power() function and print the first element again, hoping it to change. Given the declaration of power() that I have written, you could achieve it by doing it like so:

#include <iostream>

void power(int x[5])
{
    x[0]=12;
    x[1]=23;
    x[2]=234;
    x[3]=344;
    x[4]=232;
}

int main()
{
    int x[5] = {1,2,3,4,5};

    std::cout << x[0] << ' ';
    power(x);
    std::cout << x[0] << std::endl;
}

That outputs: 1 12.

Leave a Comment