0

I am getting segmentation fault for this code I don't know what is wrong. it is running fine if input is given already but fails when we try to take input from user.

`

#include <bits/stdc++.h>
using namespace std;

void reverseArray(int arr[], int s,int e){
    if (s<e){
        swap(arr[s],arr[e]);
        reverseArray(arr,s++,e--);
    }
}

int main() {
    //code
    int t;
    cin>>t;
    while (t--)
    {
    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++)
        cin>>arr[i];
    reverseArray(arr,0,n-1);

    for(int i=0;i<n;i++)
        cout<<arr[i]<<" ";
   
    cout<<endl;
    }
}    `
1
  • 2
    Unrelated: once you fix this to use the proper pre vs post increment/decrement, challenge yourself and see if you can figure out how to do it recursively with only two arguments rather than three. And fyi, int arr[n]; isn't standard C++. Variable length arrays are a vendor-dependent extension, as is #include <bits/stdc++.h>, You should break that habit and not use either. Commented Sep 3, 2022 at 6:16

1 Answer 1

1

You meant

reverseArray(arr,s+1,e-1);

This would also work, (although it does unnecessary work by modifying the s and e variables).

reverseArray(arr,++s,--e);

The problem with s++ and e-- is that the value they return is the value of s and e, so you are passing unchanged values to your recursive call, leading eventually to a stack overflow.

Essentially your misunderstanding is about the difference between the return value of an operation and the side affect. The side effect of ++ and -- is to modify the variable. But this is irrelevant, what gets passed to the recursive call is the return value of the expression.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.