Reversing an Array

Hello, I need help with this assignment I'm working on. I have to write a program that has a dynamically allocated array, of which the user can input the size and values, and copy the values of the user-created array into a new dynamically allocated array in reverse order. Here is what I have and I'm getting this error message from the compiler:

9.10.cpp: In function ‘int main()’:
9.10.cpp:26:29: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
revArray=reverse(array, size);
^
9.10.cpp: In function ‘int reverse(int*, int)’:
9.10.cpp:45:8: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
return revArray;
^


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//Reverse Array
#include<iostream>
using namespace std;
int reverse(int[], int);
int main()
{
int size;
cout<<"This program accepts an array and reverses the order.\n";
cout<<"How many numbers would you like to enter?\n";
cin>>size;
int *array;
int *revArray;
array= new int[size];
revArray=new int[size];
for(int i=0; i<size; i++)
{
cout<<"Enter number "<<(i+1)<<".\n";
cin>>array[i];
}
cout<<"The contents of the array are: ";
for(int i=0; i<size; i++)
{
cout<<array[i]<<" ";
}
cout<<"\n";
revArray=reverse(array, size);
cout<<"The contents of the reversed array are: ";
for(int i=0; i<size; i++)
{
cout<<revArray[i]<<" ";
}
cout<<"\n";
delete [] array;
delete [] revArray;
return 0;
}
int reverse(int array[], int size)
{
int *revArray;
revArray=new int[size];
for(int i=0; i<size; i++)
{
revArray[i]=array[size-i];
}
return revArray;
}
You're getting those errors because reverse is supposed to return an int, but you're actually returning (and assigning to) an int* variable.

It seems to me that you have two options:
1) Have reverse take (as parameters) an already allocated array, the original array, and the size, store the reverse of the original array into the other array, and return nothing (void).
Then reverse might look something like
1
2
3
4
5
6
void reverse(int* dest, const int* src, int size)
{
    // Assume that sufficient memory has already been allocated for 'dest'
    for (int i = 0; i < size; ++i)
        dest[i] = array[size-i-1];
}

2) Have reverse allocate the memory for the reversed array and just return that.
In that case, you shouldn't be allocating any memory for revArray in main:
1
2
3
4
5
6
7
int* reverse(const int* array, int size)
{
    int* revArray = new int[size];
    for (int i = 0; i < size; ++i)
        revArray[i] = array[size-i-1];
    return revArray;
}

My gut feeling tells me to prefer the first, but I guess it's ultimately your choice....
Thanks! I'll have to go with the second option because the assignment explicitly says that the function must return a pointer to the reversed array and the professor is very picky about that sort of thing.
Topic archived. No new replies allowed.