[英]C++ pointer gets overwritten in for loops
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.例如,给定以下代码片段,用户输入 1 和 2。我希望pNums
数组包含 2 个指向 2 个整数的指针,分别持有值 1 和 2。
But instead, the console prints out 2
and 2
;但相反,控制台打印出2
和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?例如,如果我们不知道用户将输入多少个数字,并且我们有一个while
循环而不是for
循环怎么办? Until some conditions are met, we want to keep creating new pointers and store them into a pNums
vector?在满足某些条件之前,我们想继续创建新的指针并将它们存储到pNums
向量中吗?
There is only one num
, and you are overwriting that.只有一个num
,您正在覆盖它。 (And then causing Undefined Behavior, but never mind that.) (然后导致未定义的行为,但没关系。)
There are two simple ways to avoid this mistake.有两种简单的方法可以避免这个错误。
1) Store objects, not pointers: 1)存储对象,而不是指针:
int nums[2];
for(int i = 0; i < 2; i++){
cin >> nums[i];
}
2) Use dynamic allocation: 2)使用动态分配:
int* pNums[2];
for(int i = 0; i < 2; i++){
int *p=new int;
cin >> *p;
pNums[i] = p;
}
for(int i = 0; i < 2; i++){ int num; //< this is num. It lives here. cin >> num; pNums[i] = (&num); //< you have taken the address of num (twice!) } // here is when 'num' is destroyed (no longer in scope) // so this is now pointing at something that doesn't exist. cout << (*pNums[0]) << endl;
The pointers that you are storing in pNums
are to two instances of the variable num
in the for
block.您存储在pNums
中的指针指向for
块中变量num
两个实例。 There is one instance of the variable in each for
loop iteration and these variables live only until the end of their respective iteration of the for
loop body is reached.在每个for
循环迭代中都有一个变量实例,这些变量仅在到达它们各自的for
循环体迭代结束时才有效。
Therefore your pointers will be invalid when the for
loop exits and so trying to dereference them with eg *pNums[0]
causes undefined behavior .因此,当for
循环退出时,您的指针将无效,因此尝试使用例如*pNums[0]
取消引用它们会导致未定义行为。
Don't store pointer, store values:不要存储指针,存储值:
#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;
}
and if you need a variable number of entries in the array, use std::vector
.如果您需要数组中可变数量的条目,请使用std::vector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.