簡體   English   中英

C / C ++:如何正確將“ unsigned int *”值轉換為“ unsigned int”?

[英]C/C++: How to properly convert “unsigned int *” value to “unsigned int”?

我有一個“ unsigned int *”值,我需要將其轉換為簡單的“ unsigned int”,以便將其傳輸到函數中。 但是,不幸的是,當我嘗試進行簡單的轉換時,值被更改了:

Code:

unsigned int * addr;

...

fprintf(stdout, "=== addr: %08x ===\n", addr); fflush(stdout);
fprintf(stdout, "=== casted addr: %08x ===\n", (unsigned int)addr);


Output:

=== addr: fc880000 ===
=== casted addr: 400eff20 ===

請告訴我,如何正確轉換此值,以便在轉換過程中它不會改變?

只需使用*addr 這是有效的,應該始終有效。 如果你需要得到的指針,而不是指向指針,你需要更大的類型值的價值 通常, unsigned int*值為64位, unsigned int只有32位。

當您聲明一個指針時,就像

unsigned int * addr;

該指針的值將是它所指向的unsigned int的地址。

當您想要獲取unsigned int的值時,它指向您使用解引用運算符*

unsigned int value = *addr;

因此,您在第二行輸出中看到的是addr指向的內容。

如果您有某種類型的指針,並且需要將其轉換為該類型,則只需要引用該指針即可。

void foo(unsigned int some_value);

...

int main()
{

    unsigned int * addr = 0x12345678; // some address holding an unsigned int
    foo(*addr);  // some function taking a unsigned int

無需在此處進行任何類型轉換,因為您無需更改類型。 請注意,您的代碼中的“值”不變:

// prints the address
fprintf(stdout, "=== addr: %08x ===\n", addr); 

// prints the value at that address
fprintf(stdout, "=== casted addr: %08x ===\n", *(unsigned int *)addr);

您沒有更改值。

fprintf(stdout, "=== addr: %08x ===\n", addr); fflush(stdout); 

您正在訪問指針的地址。

fprintf(stdout, "=== casted addr: %08x ===\n", *(unsigned int *)address);

您正在訪問所指向的值。

暫無
暫無

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

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