簡體   English   中英

如何將 int* 轉換為 int

[英]How to convert int* to int

給定一個指向int的指針,我怎樣才能獲得實際的int

我不知道這是否可能,但有人可以建議我嗎?

在指針上使用 * 來獲取指向的變量(取消引用)。

int val = 42;
int* pVal = &val;

int k = *pVal; // k == 42

如果您的指針指向一個數組,則取消引用將為您提供該數組的第一個元素。

如果您想要指針的“值”,即指針包含的實際內存地址,則對其進行強制轉換(但這通常不是一個好主意):

int pValValue = reinterpret_cast<int>( pVal );

如果您需要獲取指針指向的值,那么這不是轉換。 您只需取消引用指針並提取數據:

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

希望這可以幫助。

使用解引用運算符*例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM