簡體   English   中英

如何使用 (s)printf 將地址完美地打印到 c 字符串或標准輸出中?

[英]How to print an address flawlessly into a c-string or stdout using (s)printf?

盡管我不是“C”方面的專家,但我想給我的侄子一些指針雜技的初學者課程。 因此,我需要將地址放入字符串中以讓他閱讀。 我研究了關於“地址到字符串”的兩個主題:

在沒有完美工作的部分

不是我要找的

我之前嘗試過的,

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

int main(int argc, char *argv[]) {
int Aa = 90;
// printf("\nAa got the address %p", &Aa); // of course working  !!
printf("\nAa got the address %x", &Aa);
printf("\nAa got the value %d \n", Aa);
return 0; }

導致無害但一點也不受歡迎的警告:

格式“%x”需要“unsigned int”類型的參數,但參數 2 的類型為“int*”[-Wformat=]

當我從我發現的東西中選擇簡單的方法時:

...
char strAddress[] = "0x000000000"; 
sprintf(strAddress, "0x%x", &Aa);
...

當然,在嘗試寫入 DC 時,我收到了與“sprintf”相同的警告。

問題是:僅使用 c-string 時如何避免警告?

你喜歡嗎?

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

int main() {
    int Aa = 90;
    printf("0x%" PRIxPTR "\n", (uintptr_t)&Aa);
}

輸出類似: 0x7ffddc89907c

無論如何,“%p”必須工作大聲笑。

如果要 output 地址,只需使用%p&返回變量的地址。

#include<stdio.h>

int Aa = 90;

void main()
{
    printf("%p", (void *) &Aa);
}

請注意,要使用printf ,您必須包含stdio.h

要打印地址,請使用%p格式說明符,並將參數強制轉換為void* 喜歡

#include<stdio.h>

int main (void)
{
    int var = 12345;
    printf("The address is %p\n", (void*) &var); // add 0x in front of %p if you like

    return 0;
}

暫無
暫無

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

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