If you are writing a C++ program then use the operator new
instead of the C function malloc
.
For example
unsigned *output = new unsigned[5];
And you always should free all the allocated memory when it is not required any more.
Your function has undefined behavior because in this statement
output[i] = arr[5 - i];
when i
is equal to 0
there is an access to memory outside the passed array because in this case the statement is look like
output[0] = arr[5];
Also the function parameter should have the qualifier const
because passed arrays are not changed within the function.
Also using the magic number 5
within the function makes the function useless.
The program can look the following way
#include <iostream>
#include <iterator>
unsigned * reverseArray( const unsigned *arr, size_t n )
{
unsigned *output = nullptr;
if ( n != 0 )
{
output = new unsigned[n];
for ( std::size_t i = 0; i < n; ++i )
{
output[i] = arr[n - i - 1];
}
}
return output;
}
int main()
{
unsigned array1[] = { 10, 20, 30, 40, 50 };
const std::size_t N = std::size( array1 );
unsigned *array2 = reverseArray( array1, N );
for ( std::size_t i = 0; i < N; i++ )
{
std::cout << array2[i] << ' ';
}
std::cout << std::endl;
delete [] array2;
return 0;
}
Pay attention to that there is standard algorithm std::reverse_copy
that can be used. Using this algorithm the program can look the following way
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
unsigned array1[] = { 10, 20, 30, 40, 50 };
const std::size_t N = std::size( array1 );
unsigned array2[N];
std::reverse_copy( std::begin( array1 ), std::end( array1 ),
std::begin( array2 ) );
for ( const auto &item : array2 )
{
std::cout << item << ' ';
}
std::cout << std::endl;
return 0;
}
There is no need to allocate dynamically a new array. Otherwise you could write for example
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
unsigned array1[] = { 10, 20, 30, 40, 50 };
const std::size_t N = std::size( array1 );
unsigned *array2 new unsigned[N];
std::reverse_copy( std::begin( array1 ), std::end( array1 ),
array2 );
for ( std::size_t i = 0; i < N; i++ )
{
std::cout << array2[i] << ' ';
}
std::cout << std::endl;
delete [] array2;
return 0;
}
If you need to reverse the source array then use another algorithm std::reverse
the following way
std::reverse( std::begin( array1 ), std::end( array1 ) );