我正在开发一个使用指针来设置变量值的程序。例如,要将 price 设置为 19.95,我不会使用变量 price,而是使用指针变量 *p_price。
下面的代码产生以下结果:
address of price=0x22fec8
contents of price=19.95
address of *p_price=0x22ffe0
contents of p_price=0x22ffe0
contents of *p_price=19.95
我试图让中间的那个显示 p_price 的地址,而不是 *p_price。但是,将代码更改为显示 &p_price 会导致程序崩溃,而没有任何错误提示。
price的地址应该是&*p_price
p_price 的地址是 &price?
#include <iostream>
#include <iomanip>
#include <random> // needed for Orwell devcpp
using namespace std;
int main(){
float * p_price;
*p_price=19.95;
float price = *p_price;
cout <<"address of price="<<&price<<endl;
cout <<"contents of price="<<price<<endl;
cout <<"address of *p_price="<<&*p_price<<endl;
cout <<"contents of p_price="<<p_price<<endl;
cout <<"contents of *p_price="<<* p_price<<endl;
}
最佳答案
问题是你给一个你没有分配内存的指针赋值。您正在取消引用 *p_price
,然后将 19.95
分配给它,但是您要取消引用哪个地址?因为没有为其分配内存,它指向内存中的某个随机位置,这会导致 UB(未定义行为)
float * p_price; // no memory is allocated!!!!
// need to allocate memory for p_price, BEFORE dereferencing
*p_price=19.95; // this is Undefined Behaviour
关于c++ - 使用指针设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27072651/