cin >> x affecting value y...?

Hello there, I am not sure why this is exactly happening. I have forgotten most of my C++ coding and decided to do it again. It's suppose to be an easy code. Basically, without cin the values of the dynamic array py are not affected if you erased that part from the code. But, with cin, the values go undefined all the way. Probably, and I am pretty sure, a beginner mistake on my part, but I am not sure which.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
    int x = 0;
    int y = 0;
    int*py;
    py = new int[y];

    y = 5;
    for (int i = 0; i < y; i++){py[i]=0; cout << py[i];}

    cout << endl;
    cin >> x;

    for (int i = 0; i < y; i++){cout << py[i];}
}


It produces:

1
2
3
4
5

00000 // This is normal
33 // Random input
00115900411600


Any ideas, and solutions to the problem?
Edit:
And it seems to only be happening on py[2]. Expanding it just makes the random value stay there.
Last edited on
the size py points to is zero, since y variable is zero upon allocating dynamic memory, then you later changed it to 5.

Perhaps you want to change y before allocating memory

EDIT
You also didn't delete[] py
Last edited on
Topic archived. No new replies allowed.