使用指针设置变量

时间:2014-11-22 00:31:12

标签: c++ pointers

我正在研究一个使用指针来设置变量值的程序。例如,要将价格设置为19.95,我不会使用变量价格,而是使用指针变量* 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。但是,将代码更改为display& p_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;
}

4 个答案:

答案 0 :(得分:1)

问题是您为没有分配内存的指针赋值。您正在解除引用*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

答案 1 :(得分:1)

int main(){
     float * p_price;
    *p_price=19.95;

应该是

int main(){
    float price;
     float * p_price = &price;
    *p_price=19.95;

如果你想使用它,指针必须指向某个东西。

答案 2 :(得分:0)

在您的代码中p_price是指向float的指针,但在将其指定为指向float实例之前,您取消引用它。试试这个:

int main(){
    float price;
    float * p_price = &price;
    *p_price=19.95;

    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;
    return 0;
}

答案 3 :(得分:0)

嗯,我可以看到你正在创建指向float的指针,但是这个指针指的是什么。

int main() {
    //Bad code
    float* pointer;    //Okay, we have pointer, but assigned to nothing
    *pointer = 19.95f; //We are changing value of variable under pointer to 19.95...
                       //WAIT what? What variable!?
    //////////////////////////////////////////////////////////////////////
    //Good code
    float* pointer2 = new float(0f);
    //We are creating pointer and also variable with value of 0
    //Pointer is assigned to variable with value of 0, and that is good
    *pointer2 = 19.95f;
    //Now we are changing value of variable with 0 to 19.95, and that is okay.
    delete pointer2;
    //But in the end, we need to delete our allocated value, because we don't need this variable anymore, and also, read something about memory leek
    return 0;
}