簡體   English   中英

C指針位置,十進制和十六進制

[英]C Pointer Location, Decimal and Hexadecimal

我正在嘗試學習如何以十進制和十六進制顯示指針值。 在下面,您可以看到我創建一個值並嘗試使用指針打印出該值和值的位置。

請使代碼正常工作,以便以十進制和十六進制格式輸出值

double val= 1;
printf("The value of val : %f\n",val);


double *ptr;
ptr= &val;

printf("dereference *ptr= %f\n", *ptr);

//Display the location of val with and without pointer use in decimal and hex


//decimal
printf("location of val in decimal with ptr is: %p\n",(void *) ptr); 
printf("location of val in decimal without a pointer is: %p\n",(void *) &val ); 

//hexadecimal THIS IS NOT WORKING 
printf("location of val in hex with ptr is: %#x\n", (void *) ptr); 
printf("location of val in hex without a pointer is: %#x\n", (void *) &val ); 

%p格式為void *並以實現定義的格式打印。 如果要抓住控制權,請使用<stdint.h>的類型和<inttypes.h>格式(在C99中首次定義):

#include <inttypes.h>

printf("Location in decimal:  %" PRIuPTR "\n", (uintptr_t)ptr);
printf("Location in hex:      0x%.8" PRIXPTR "\n", (uintptr_t)ptr);
printf("Location in octal     %#" PRIoPTR "\n", (uintptr_t)ptr);

等等。

uintptr_t類型(名義上是可選的,但所有實際實現都應定義它)是一個無符號整數類型,其大小足以容納指向對象的指針(變量;不一定足夠容納函數指針)。 諸如PRIuPTR的名稱為uintptr_t類型定義了正確的轉換說明符(該值是特定於平台的)。

請注意,如果使用<inttypes.h> ,則無需包括<stdint.h>

C通常以十六進制數返回內存地址,因此您只需要使用%p。 至於十進制表示形式,可以使用類型轉換:

int rand1 = 12, rand2 = 15;

printf("rand1 = %p : rand2 = %p\n\n", &rand1, &rand2); 
// returns hexadecimal value of address

printf("rand1 = %d : rand2 = %d\n\n", (int) &rand1, (int) &rand2);  
// returns decimal value of address

不要忘記包含#include <inttypes.h>

如評論所建議,最好這樣做:

//hexadecimal
printf("Location in hex:      0x%.8" PRIXPTR "\n", (uintptr_t)ptr);
printf("Location in hex:      0x%.8" PRIXPTR "\n", (uintptr_t)&val);

如果您對unitptr_t感到不舒服,請想象您正在轉換為unsigned int 並不一樣,但這是一個開始。

有關更多信息,請閱讀答案。

另外,您可能想看看%p%x之間的區別

對於十進制,請使用%lu(長無符號長整數)代替%p。此外,無需使用常規printf函數進行(void *)強制轉換

像這樣:

//decimal
printf("location of val in decimal with ptr is: %lu\n",ptr); 
printf("location of val in decimal without a pointer is: %lu\n",&val );

以十六進制格式打印指針時,可以使用%p代替%x。 像這樣:

//hexadecimal
printf("location of val in hex with ptr is: %#x\n", ptr); 
printf("location of val in hex without a pointer is: %p\n", &val ); 

暫無
暫無

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

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