@MattaGodus when we are starting error occurs.I have mentioned out the problems and the and way to fix them.
Problems in the code:
int* areverse[10];
should be :
int * areverse = new int[size];//what ever the size it
Problem with this line int* areverse[10]
is when the function returns stack area is cleared.
Using the new keyword we are creating variable inside of heap now even our function returns this area remains.
arr[c] = areverse[s];
we should be assigning areverse
from arr
return areverse[s];
It should be:
return areverse;
Code with bug fixed:
#include <iostream>
using namespace std;
int *reverse_Array(int , int*);
////////Reverses an array of integer//////////
int* reverse_Array(int size, int* arr){
int * areverse = new int[size];//use new keyword to allocated new memory inside method
for (int c = size -1 ; c >= 0; c--)
areverse[size-1 -c] = arr[c]; // the issue happens here with the =
return areverse;
}
////////Main////////
int main(){
int arr[] = {1, 2, 3, 4};
int size = sizeof(arr) / sizeof(int);
int * rarr = reverse_Array(size, arr);
for (int i = 0;i<size; i++)
cout<<rarr[i]<<" ";
cout<<endl;
return 0;
}
output:
$ g++ main.cpp && ./a.out
4 3 2 1