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

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;
}