Reversing Arrays Using Recursion

Is there a way to reverse an array by ONLY passing in the array? It seems that it is pretty easy if both the array and the number of the elements in the array are passed but not just the array. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
using namespace std; 

void reverse (int array[])
{
        //some code here
}

int main () 
{
	int x = 0; 
	cout << "How many numbers? " << endl;
	cin >> x; 
	int array [x]; 
	for (int i = 0; i < x; i++)
	{
		array[i] = i;
	}

	reverse (array); 
}
Your
1
2
3
4
void reverse( int array[] )
{
        //some code here
}

Is effectively the same as
1
2
3
4
void reverse( int  * array )
{
        //some code here
}

The problem in those is that the function does not know that the pointer actually points to an array nor how many elements such array might have.


Edit:
Your line 17 is not supported by standard C++. The compiler should generate instructions that reserve memory from stack for the array when the function is called. However, nobody knows how much memory should be allocated. Not when compiling. Not when starting the function.

If you want the user to determine the size of the array, then you have to allocate memory for the array dynamically. The standard library has std::vector for that purpose.
Last edited on
@keskiverto

Thank you for your response.

So does that mean that reversing an array by just passing the array is impossible?

Best regards,
Jae
So does that mean that reversing an array by just passing the array is impossible?

No. It's just not a good idea. You could use global variables instead of passing parameters, but that isn't terribly good practice.
@cire

I understand. Thank you so much!

Best regards,
Jae Kim
Topic archived. No new replies allowed.