使用指针设置变量
using pointers to set variables
我正在开发一个使用指针来设置变量值的程序。例如,要将价格设置为 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;
}
相关文章:
- 将双精度变量设置为另一个变量的值
- 将变量设置为类型模板
- 如何为具有整数名称的变量设置位集
- 在 c++ 中将多个变量设置为相同的值
- 我是否必须在类中的所有变量C++设置为 private?
- 在C 中,如何使用变量设置Char Grid2d [x] [y]
- 如果将变量设置为等于新对象,旧对象会发生什么情况?
- C++ 给出编译器错误,将一个(静态)常量全局变量设置为另一个静态常量变量
- 是否可以将类成员变量设置为类函数的结果?
- 将 c++ 代码中的当前用户环境变量设置为对其他进程(如 cmds)可见
- 此CMAKE错误意味着什么?我的变量设置为未发现
- 如何基于用户设置的初始变量设置一组常数值
- 如何使用const成员变量设置数组大小
- 使用变量设置数组长度
- 使用变量设置bitset的大小
- 在C 中,如何将派生类中的私有变量设置为基类的输入值
- C 标量变量设置为零值
- C 定义变量设置值
- 正在将类级别的2D数组变量设置为传入值-C++
- 是否有C++标准类在作用域出口处将变量设置为值