For starters the return type int *
of the function does not make sense.
int* mirror(int* p[], int n) {
It is better to declare the function as having the return type void
.
If you have an array of pointers of the type int *
then a pointer to its elements has the type int **
.
Moreover the user can pass 0 as the second argument. You should check this case.
The reason of the exception can be the array contains invalid pointers that point outside of the original array.
Also if the array of pointers is formed such a way that it is not necessary that for example the first pointer points to the first element of the original array then you function will not work.
The function can be defined like
void mirror( int * p[], size_t n )
{
if ( n != 0 )
{
for ( int **first = p, **last = p + n; first < --last; ++first )
{
int tmp = **first;
**first = **last;
**last = tmp;
}
}
}
Here is a demonstrative program
#include <iostream>
void mirror( int * p[], size_t n )
{
if ( n != 0 )
{
for ( int **first = p, **last = p + n; first < --last; ++first )
{
int tmp = **first;
**first = **last;
**last = tmp;
}
}
}
int main()
{
const size_t N = 5;
int a[N] = { 10, 30, 30, 40, 50 };
int * b[N] = { a, a + 1, a + 2, a + 3, a + 4 };
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
mirror( b, N );
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
10 30 30 40 50
50 40 30 30 10
Pay attention to that instead of swapping elements "manually" you could use the standard function std::swap
.