c++ - 使用指针设置变量

标签 c++ pointers

我正在开发一个使用指针来设置变量值的程序。例如,要将 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/

相关文章:

c++,如何以给定的概率随机选择数字

c++ - LLDB:如何检查 unordered_map

c++ - 在 Metal 着色器代码中,如何定义函数的输入/输出参数变量?

c++ - 我们可以在将对象转换为 (char *) 后取回对象吗

c - 通过引用传递c中的指针数组

c++ - 模板化类型转换运算符和偏特化

c++ - 编译时 C++ 项目抛出错误 C2228,这不是预期的,因为控件在运行时未到达该点

c - 意外的指针随机变化。为什么会改变呢?破坏指针算术

c - 带字符串赋值的数组对象指针会导致崩溃

c++ - 推回 vector 指针时如何解决读取访问冲突