Function returning an array

Mar 13, 2013 at 12:53am
Hello, I just started a university course and one of the assignments is to let the user enter in an array, then call a reverse function to reverse the array which sends this array back to the main function, then the main function prints it out.
I can get everything to work except the reverse function as it wont send back an array to the main function. Any help is appreciated.
Thank you

#include <iostream>
using namespace std;

int* reverse (int a)
{
int* z;
int i;
int test [3];
z = test;
for(n=2; n>-1; n--)
{
z [i] = a [n];
i++;
}
return z;
}

int main ()
{
int e_array [3];
int n;

cout << "Please enter 3 numbers: " << endl;
for(n=0; n<3; n++)
{
cin >> e_array[n];
}

int* r_array = reverse(e_array);

cout << "The 3 numbers reversed are: " << endl;
for(n=0; n<3; n++)
{
cout << r_array[n] << endl;
}
}
Mar 13, 2013 at 1:10am
Please use code tags.

In reverse() 'i' is uninitialized. You're changing the value of data outside of the array.
Also the type of the parameter is wrong. Currently it accepts a single int, not an array of them.

By the way there's no need for 'z'. You can change the values directly using test[i] and then return test;.
Last edited on Mar 13, 2013 at 1:13am
Mar 13, 2013 at 2:13am
Sorry about the lack of code tags I havent submitted before.

And thankyou i got my code to work :)
Topic archived. No new replies allowed.