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;
    }
}    `
  • 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 `](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h), You should break that habit and not use either. – WhozCraig Sep 03 '22 at 06:16

1 Answers1

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.

john
  • 85,011
  • 4
  • 57
  • 81