0
int* reverse_Array(int size, int* arr)
{
    int* areverse[10];

    int s = 0;

    for (int c = 10; c > 0; c--)

        arr[c] = areverse[s]; // the issue happens here with the =

    return areverse[s];
}

The issue happens with the = between arr[c] and areverse[s]

I tried a couple fixes but each one doesn't really fix it.

I am writing code that should reverse a array "(using a function by returning a pointer/array)"

Eddymage
  • 1,008
  • 1
  • 7
  • 22

2 Answers2

1

If you're "allowed" to use vectors, you can use a simple example like this.

#include <vector>
#include <algorithm>

template<typename T>
std::vector<T> reverse_array(const std::vector<T>& array)
{
    std::vector<T> t = array;
    std::reverse(array.begin(), array.end());
    return t;
}
Menace
  • 417
  • 3
  • 10
0

@MattaGodus when we are starting error occurs.I have mentioned out the problems and the and way to fix them.

Problems in the code:

  1. 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.

  1. arr[c] = areverse[s];

we should be assigning areverse from arr

  1. 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 
Udesh
  • 2,415
  • 2
  • 22
  • 32
  • 1
    `"stack area is cleared"` -- What exactly is "cleared" supposed to mean? Overwritten? [That is not necessarily the case](https://stackoverflow.com/q/6441218/12149471). Also, ISO C++ does not have a notion of a "stack" (even if most C++ compiler implementations use a stack). ISO C++ only has a notion of [object lifetime](https://en.cppreference.com/w/cpp/language/lifetime). When a function returns, in general, the lifetime of its local variables end (there are some exceptions though, such as `static` variables). – Andreas Wenzel Feb 12 '22 at 19:44