【发布时间】:2020-04-13 17:21:40
【问题描述】:
给定一个指向int的指针,我怎样才能获得实际的int?
我不知道这是否可能,但有人可以告诉我吗?
【问题讨论】:
-
你说你不确定这是否可能。考虑一下:如果这不可能,那么指针的用途是什么?
-
我承认这是个愚蠢的问题
给定一个指向int的指针,我怎样才能获得实际的int?
我不知道这是否可能,但有人可以告诉我吗?
【问题讨论】:
在指针上使用 * 来获取指向的变量(取消引用)。
int val = 42;
int* pVal = &val;
int k = *pVal; // k == 42
如果你的指针指向一个数组,那么解引用会给你数组的第一个元素。
如果你想要指针的“值”,也就是指针所包含的实际内存地址,然后强制转换它(但这通常不是一个好主意):
int pValValue = reinterpret_cast<int>( pVal );
【讨论】:
int 是一个很好的类型来转换指针吗? #include <cstdint> 和 uintptr_t 不是更便携吗?
如果您需要获取指针指向的值,那么这不是转换。您只需取消引用指针并提取数据:
int* p = get_int_ptr();
int val = *p;
但如果你真的需要将指针转换为int,那么你需要强制转换。如果您认为这是您想要的,请再想一想。可能不是。如果您编写的代码需要这种结构,那么您需要考虑重新设计,因为这显然是不安全的。尽管如此:
int* p = get_int_ptr();
int val = reinterpret_cast<int>(p);
【讨论】:
我不能 100% 确定我是否理解您想要的:
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
希望这会有所帮助。
【讨论】:
ctrl+f 和搜索 cast 找到错误的转换这一事实证明了使用 C++ 样式转换的合理性。
使用取消引用运算符* 例如
void do_something(int *j) {
int k = *j; //assign the value j is pointing to , to k
...
}
【讨论】:
你应该严格区分你想要什么:强制转换或取消引用?
int x = 5;
int* p = &x; // pointer points to a location.
int a = *p; // dereference, a == 5
int b = (int)p; //cast, b == ...some big number, which is the memory location where x is stored.
您仍然可以将 int 直接分配给一个指针,只是不要取消引用它,除非您真的知道自己在做什么。
int* p = (int*) 5;
int a = *p; // crash/segfault, you are not authorized to read that mem location.
int b = (int)p; // now b==5
您可以不使用显式转换 (int)、(int*),但您很可能会收到编译器警告。
【讨论】:
使用 * 取消引用指针:
int* pointer = ...//initialize the pointer with a valid address
int value = *pointer; //either read the value at that address
*pointer = value;//or write the new value
【讨论】:
int Array[10];
int *ptr6 = &Array[6];
int *ptr0 = &Array[0];
uintptr_t int_adress_6 = reinterpret_cast<uintptr_t> (ptr6);
uintptr_t int_adress_0 = reinterpret_cast<uintptr_t> (ptr0);
cout << "difference of casted addrs = " << int_adress_6 - int_adress_0 << endl; //24 bits
cout << "difference in integer = " << ptr6 - ptr0 << endl; //6
【讨论】: