Why is a variable I've scanned changing upon scanning a separate array?

Viewed 55

I'm going through the challenges for C++ on HackerRank and I've gotten stuck at the arrays introduction. It's giving me a sample input of

4
1 4 3 2

Where n=4 is the size of the array and the following line gives the array with n random integers. I ran into an issue with n=4 changing after my first for loop when answering the question, so I've been messing with it to try to understand it.

At the moment, I'm simply trying to scan the sample input numbers but n keeps changing once I've scanned the last element of the array:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    int n, arr[n];
    scanf("%d", &n);
    printf("%d \n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        printf("%d ", arr[i]);
        printf("n=");
        printf("%d ", n);
    }
    printf("\n%d", n);
    return 0;
}

which gives me the following output:

4
1 n=4 4 n=4 3 n=4 2 n=2
2

Can anyone explain why n changes to a 2 after the final loop and stays as n=2 for all subsequent uses? How is it affected when I haven't assigned it to anything? This is the only sample input they give me as practice but they try a lot more with 1<=n<=1000 after I submit it and I want to understand it without cheating.

1 Answers

First in C++, the size of an array must be a compile-time constant.So, take for example the following code snippets:

int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression

The correct way to write the above would be:

const int n = 10;
int arr[n]; //CORRECT

Similarly, the following(which you did in your code example) is incorrect:

int n, arr[n]; //INCORRECT, Note n has garbage value and using this garbage value leads 
              //to undefined behavior and also n is not a constant expression

Note the above statement has 2 problems:

First since you have not initialized n, it has an indeterminate value and you're using that value which is undefined behavior.

Second n is not a constant expression.

To solve this,you should use std::vector instead of using built in array as shown below:


#include <vector>
#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    std::cin >> n;
    //create a vector of size n 
    std::vector<int> arr(n);
    
    printf("%d \n", n);
    //iterator through the vector
    for (int &element: arr) {
        std::cin >> element ;
        std::cout<<element <<" ";
        //add other code here
    }
   
    return 0;
}
Related