c++iostreamcincout

I don't understand why cin worked differently depending on when I took the input


I was solving the hacckerrank challenge Arrays Introduction. It was a very simple question. The input was two lines. The first had size of the integer and the second line had the integers separated by space.

Example input:

4
1 4 3 2

Expected output:

2 3 4 1

The question asked to print reversed array. My solution to the problem was as below:

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n;
    int arr[n];
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    } 
    for(int i=n-1;i>=0;i--)
    {
        cout<<arr[i]<<' ';
    }   
    return 0;
}

This did not work. The output I got was: 4 1

But doing one minor change to this solutions makes everthing okay. So this works:

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    } 
    for(int i=n-1;i>=0;i--)
    {
        cout<<arr[i]<<' ';
    }   
    return 0;
}

I don't understand why putting cin before and after the array declaration made such a difference in the output. If anyone can help me understand, I'd really appreciate it. Thankyou.


Solution

  • You are using a variable-length array (i.e. an array whose size is not a compile-time constant). Standard C++ does not support them, but it appears that you are using a compiler that supports them as an extension to the language.

    In C++, arrays have a fixed length that cannot be changed after the array has been created. This also applies to variable-length arrays.

    In both programs, you are specifying that the length of the array is n. However, in your first program, when the array is created, n has not been assigned a value yet, so the value of n could be less than the value that you will later read from standard input. In that case, the size of the array will not be sufficient to store the values, which means what you will be writing to the array out of bounds, invoking undefined behavior.

    Your second program does not have this problem, because you are creating the array after the value of n has been set. This means that the size of the variable-length array is being set correctly.

    If you want an array-like data structure whose size you want to be able to change dynamically (even after creation), then you should be using a std::vector instead of a variable-length array. In contrast to variable-length arrays, std::vector is fully supported by standard C++.