As others have mentioned, what is happening is that you are allocating empty arrays in the stack, and then accessing past the bounds of said array. This has far more dire consequences than you may at first realize.
The first of which is, as @Jack mentioned, that writing past a[0]
will start writing in b
, giving you duplicate and nonsensical values at the end of your program. Perhaps less obvious is the fact that you will also start overwriting t
and i
, since they are allocated in the stack after a
and b
. To illustrate my point, look at the output below:
Amount of numbers: 2
Enter number for A1: 1
Enter number for B1: 2
Enter number for A2: 3
Enter number for B2: 4
Enter number for A3: 5
Enter number for B3: 6
a[0] 0x7fffffffe2e0 -> 1
b[0] 0x7fffffffe2e4 -> 3
a[1] 0x7fffffffe2e4 -> 3
b[1] 0x7fffffffe2e8 -> 5
a[2] 0x7fffffffe2e8 -> 5
b[2] 0x7fffffffe2ec -> 2
a[3] 0x7fffffffe2ec -> 3
b[3] 0x7fffffffe2f0 -> 4197280
a[4] 0x7fffffffe2f0 -> 4197280
b[4] 0x7fffffffe2f4 -> 0
t 0x7fffffffe2e8 -> 5
i 0x7fffffffe2ec -> 5
You'll note that the program does not behave as expected, and you are prompted for A/B3, not just the expected 2. That is because t
is overwritten when b[1]
or a[2]
are written to, as they all correspond the the same address, which of course makes the loop condition fail.
To allocate arrays in the stack, a size has to be provided at compile time. int a[10]
, etc. This is used when the size is known prior to execution. If the size unknown, as is your case, you can allocate an array in the heap with new[], as below.
cout << "Amount of numbers: ";
cin >> t;
int* a = new int[t];
int* b = new int[t];
Which will of course give you the expected results:
Amount of numbers: 2
Enter number for A1: 1
Enter number for B1: 2
Enter number for A2: 3
Enter number for B2: 4
a[0] 0x603010 -> 1
b[0] 0x603030 -> 2
a[1] 0x603014 -> 3
b[1] 0x603034 -> 4
t 0x7fffffffe2d8 -> 2
i 0x7fffffffe2dc -> 2
The recommended solution is, of course, to use an std
container, namely std::vector, where the heap allocation is done for you, and you can simply write:
std::vector<int> a;
std::cin >> input;
a.push_back(input);