2016-09-24 95 views
2

如何以十進制表示法打印指針?Printf十進制表示法指針

-Wall一起編譯時,以下都不會產生所需的結果。我明白錯誤,並且想用-Wall進行編譯。但是,如何以十進制表示法打印指針呢?

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    int* ptr = malloc(sizeof(int)); 
    printf("%p\n", ptr);     // Hexadecimal notation 
    printf("%u\n", ptr);     // -Wformat: %u expects unsigned int, has int * 
    printf("%u\n", (unsigned int) ptr); // -Wpointer-to-int-cast 
    return EXIT_SUCCESS; 
} 

(這是因爲我使用的指針作爲節點標識符中的點圖形所需要,並0x..是不是有效的標識符。)

回答

7

C具有一個數據類型命名uintptr_t的,這是足夠大以容納指針。一種解決辦法是轉換(CAST)的指針(uintptr_t的),並打印如下所示:

#include <stdio.h> 
#include <stdlib.h> 
#include <inttypes.h> 

int main(void) 
{ 
    int* ptr = malloc(sizeof *ptr); 
    printf("%p\n", (void *)ptr);     // Hexadecimal notation 
    printf("%" PRIuPTR "\n", (uintptr_t)ptr); 
    return EXIT_SUCCESS; 
} 

注意%普預計一個void *指針,如果用-pedantic編譯代碼GCC將發出警告。

string format for intptr_t and uintptr_t似乎也是相關的。

1

有報告稱某些平臺在其inttypes.h文件中不提供PRI*PTR宏。如果是您的情況,請嘗試使用printf("%ju\n", (uintmax_t)ptr);

...雖然我認爲你應該有這些宏,因爲你看起來與GNU C一起工作。