Could someone explain why pointers gets overwritten when variables are declared inside a loop?
For example, given the following snippet, and the user inputs 1 and 2. I would expect that the pNums
array contain 2 pointers to 2 integers holding the value 1 and 2 respectively.
But instead, the console prints out 2
and 2
;
#include <iostream>
using namespace std;
//Input "1 2"
int main() {
int* pNums[2];
for(int i = 0; i < 2; i++){
int num;
cin >> num;
pNums[i] = (&num);
}
cout << (*pNums[0]) << endl;
cout << (*pNums[1]) << endl;
}
Why is this the case? And how do I get around it? What if, for example, we don't know how many numbers the user will put in, and instead of a for
loop, we have a while
loop? Until some conditions are met, we want to keep creating new pointers and store them into a pNums
vector?