2014-11-22 39 views
1

我正在使用指针设置变量值的程序。例如,要将价格设置为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。但是,将代码更改为显示& p_price会导致程序崩溃,而没有任何指示错误的指示。

应价的地址是& * p_price

和p_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; 
} 

回答

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 
+0

要保留p_price的内容作为地址,我应该声明一个新变量并将p_price设置为等于那个地址? – user3866044 2014-11-22 00:35:21

+0

是的。一个指针只存储一个地址,但是因为vsoftco说有些东西需要存储浮点数... – deviantfan 2014-11-22 00:36:51

+0

是的,或者做'float * p_price = new float;',现在你有一些保留的内存位置,'p_price'点。那么,您可以对其进行解除引用并将'19.95'安全地放入该内存插槽中。 – vsoftco 2014-11-22 00:36:52

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

应该

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

指针具有指向如果你想使用它的话。

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

嗯,因为我可以看到你创建的指针浮动,但这个指针指向什么。

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