-3

This is my code

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

this is my input:

4
1 4 3 2

and for some reason the Size is turning from 4 to 2 at the very end of the loop

4442

Why is this happening and how do I solve this?

  • 9
    You have undefined behavior because `Size` isn't initialized at the time you declare `arr`. – Mark Ransom Jun 01 '22 at 01:53
  • I'm an idiot. Thanks. I retraced it again and again and didn't see that lol. Thanks – Anthony Tsangarides Jun 01 '22 at 02:01
  • 3
    I highly recommend setting your compiler's warning level to maximum. It would have informed you about the use of an uninitialized value at the time of compilation. – paddy Jun 01 '22 at 02:09
  • 2
    In standard c++ `int arr[Size];` is not valid: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Jun 01 '22 at 03:24
  • @drescherjm it may not be part of the standard, but it's a popular extension allowed by some very wide spread compilers. I don't see the point of being pedantic about it. – Mark Ransom Jun 03 '22 at 02:36

0 Answers0