使用指针设置变量

using pointers to set variables

本文关键字:变量 设置 指针      更新时间:2023-10-16

我正在开发一个使用指针来设置变量值的程序。例如,要将价格设置为 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会导致程序崩溃,而没有任何问题指示。

价格地址是否应为 &*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;
}

问题是您将值分配给未为其分配内存的指针。您正在取消引用*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
int main(){
     float * p_price;
    *p_price=19.95;

应该是

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

如果要使用它,指针必须指向某些内容。

在您的代码中,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;
}

嗯,正如我所看到的,您正在创建指向浮点的指针,但是该指针不指向任何内容。

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