lundi 2 avril 2018

Variable value changing in c++

int main(){

    int n, p;
    int arr[n];

    cin >> n >> p;
    cout << p << endl;

    for(int i=0; i<n; i++){
        cin >> arr[i];
     }

    cout << p;

    return 0;
}

Could anyone please explain to me why does the value of p change in the second cout. Shouldn't it yield the same value in both instances of cout? Also, when I remove the loop in between the two cout's, then those values match. I am having trouble understanding this behaviour.

P.S. The above problem occurs only when n > p.

Aucun commentaire:

Enregistrer un commentaire