Home > database >  I am trying to reverse an array using loop in cpp ? but don't know what the problem is?
I am trying to reverse an array using loop in cpp ? but don't know what the problem is?

Time:09-17

#include <iostream>
using namespace std;

int* reverse(int arr[],int n){
    int rev[100];
    int j =0;
    for(int i=n-1;i>=0;i--){
            rev[j]=arr[i];
            j  ;
            }
    return rev;
}
int main() {
    int n;
    cin>>n;
    int arr[100];
    for(int i=0;i<n;i  ){
        cin>>arr[i];
    }
    cout<<reverse(arr,n);
}

I am trying reverse an array using loops but don't know what the error was it was returning some bin value.

CodePudding user response:

Your rev temporary resides in automatic storage. It means that the object will be gone after the function returns. While C allows you to decay rev to an int* and then return said pointer, it does not mean that this returns the object itself. You merely get a pointer to an already destroyed object. Not very useful. In fact, doing anything with this pointer will cause undefined behaviour.

Usually what you want to do is reverse things in-place. That's also how std::reverse works.

So, there are two options. If you have a completely filled c-style array, you could write a reverse function like this:

template <std::size_t N>
void reverse(int (&a)[N]) {
  // reverse a from 0 to N-1
}
reverse(a);

Or, if you have an only partially filled array, take a page out of the standard library and reverse a range, denoted by two iterators.

void reverse(int* begin, int* end) {
  /* begin points to the first entry, end points one past the last */
}
reverse(a, a n);

Of course, instead of using c-style arrays, you could use a dynamically growing array such as std::vector, which carries the actual size of the array around for you.

  •  Tags:  
  • c
  • Related