如何将int*转换为int

pau*_*op6 16 c++ pointers

给定指针int,我如何获得实际int

我不知道这是否可能,但有人可以告诉我吗?

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)


Joh*_*ing 8

如果需要获取指针指向的值,那么这不是转换.您只需取消引用指针并提取数据:

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)


phi*_*mue 5

如果我明白你的意思,我不是百分百肯定的:

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)

希望这可以帮助.

  • 为什么?C 风格转换是该语言的一部分。到底为什么要避免它们呢? (2认同)