Kla*_*aim 41
使用*on指针获取指向的变量(解除引用).
int val = 42;
int* pVal = &val;
int k = *pVal; // k == 42
Run Code Online (Sandbox Code Playgroud)
如果指针指向一个数组,则解除引用将为您提供该数组的第一个元素.
如果你想要指针的"值",那就是指针包含的实际内存地址,那么就把它投出来(但这通常不是一个好主意):
int pValValue = reinterpret_cast<int>( pVal );
Run Code Online (Sandbox Code Playgroud)
如果需要获取指针指向的值,那么这不是转换.您只需取消引用指针并提取数据:
int* p = get_int_ptr();
int val = *p;
Run Code Online (Sandbox Code Playgroud)
但是如果你真的需要将指针转换为int,那么你需要强制转换.如果您认为这是您想要的,请再想一想.可能不是.如果您编写了需要此构造的代码,那么您需要考虑重新设计,因为这显然是不安全的.然而:
int* p = get_int_ptr();
int val = reinterpret_cast<int>(p);
Run Code Online (Sandbox Code Playgroud)
如果我明白你的意思,我不是百分百肯定的:
int a=5; // a holds 5
int* ptr_a = &a; // pointing to variable a (that is holding 5)
int b = *ptr_a; // means: declare an int b and set b's
// value to the value that is held by the cell ptr_a points to
int ptr_v = (int)ptr_a; // means: take the contents of ptr_a (i.e. an adress) and
// interpret it as an integer
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.