0

I have written this c++ code to reverse a array. But it is giving wrong output. Why ??

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n,i,a,arr[n];
    cin>>n;
    for(i = 0; i<n; i++){
        cin>>arr[i];
    }
    for(i = n-1;i>-1;i--){
        cout<<arr[i]<<" ";
    }
}
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • 1
    "*It is giving wrong output.*" What was your input and expected output? What was the actual output? These are both essential parts of a [MCVE]. – scohe001 Nov 07 '19 at 21:06
  • 3
    In `int n,i,a,arr[n];` What is the value of `n` that you are using for the array? – NathanOliver Nov 07 '19 at 21:07
  • 3
    The size of an array is fixed once it's created. What do you think `n` equals to when you create `arr[n]`? Not to mention that variable-length arrays (with size not known at compile-time) are not in the standard C++, and you should be using a `std::vector` instead. Also see https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – HolyBlackCat Nov 07 '19 at 21:07

3 Answers3

4

Your code has undefined behavior. Don't count on any specific behavior.

The problem is the definition of arr.

It suffers from two problems.

  1. Variable length arrays (VLAs) are not standard C++. They are supported by some compilers as an extension.
  2. In that line, n is not initialized to a value before it is used. By assigning a value to n in cin >> n, the size of the array does not automatically change.

Use std::vector<int> for arr and your code should have predictable behavior.

int main(){
    int n,i,a;
    cin>>n;

    std::vector<int> arr(n);
    for(i = 0; i<n; i++){
        cin>>arr[i];
    }
    for(i = n-1;i>-1;i--){
        cout<<arr[i]<<" ";
    }
}

PS

Don't use #include <bits/stdc++.h>. See Why should I not #include <bits/stdc++.h>? for details.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
-1

It is not working because when you write int n, arr[n], at that time n hasn't been assigned a value. Put cin>>n before int arr[n] and it will work correctly.

Anakin
  • 1,889
  • 1
  • 13
  • 27
-3

Edit: https://stackoverflow.com/a/58756962/12335228 was quicker. Edit2: As the comment suggests, my assumption that n would be zero initialized is indeed wrong.

Oh? Wrong output you say? It works for me, even tho it shouldnt. While the logic is correct, you are well into undefined-behaviour land here:

You are declaring n and then declare arr[n] without assigning n an actual value. That means n has its default value, in the case of int 0. So your array has a capacity of 0.

C++ let's you write into that anyway, since you as the programmer are responsible for your memory. Just think of the [] operator in this case as syntactic sugar for (*arr+i), meaning the address of your array + i

astein
  • 5
  • 3
  • 1
    "*That means n has its default value, in the case of int 0*" - that's incorrect. `n` has indeterminate value, not 0. – Fureeish Nov 07 '19 at 21:14