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

问题描述

即使我不是“C”的纯粹专家,我也想给我的侄子一些指针杂技的初学者课程。因此,我需要将一个地址放入一个字符串中,让他阅读此内容。我研究了两个关于“地址到字符串”的主题

In parts not flawlessly working

Not what I looked for

我之前尝试过的,

#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=]

当我选择了what I found之外的简单方法时:

...
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”必须工作哈哈。

,

如果要输出地址,只需使用%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;
}