简体   繁体   English

在C中打印指针的地址

[英]Printing pointer's address in C

I'm reproducing printf from scrap and I need to store pointers address into a string then print it, so first I cast void* into an unsigned int then itoa it to hexadecimal but the last three char are wrong. 我正在从废料中复制printf,我需要将指针地址存储到一个字符串中然后再打印它,因此首先我将void *转换为一个无符号的int,然后将其转换为十六进制,但是最后三个字符是错误的。

int     main(void)
{
    char    str[] = "printf from scrap!";

    my_printf("MY_PRINTF:'%p'", (void*)str);
    printf("\n   PRINTF:'%p'\n\n", (void*)str);

    return (0);
}

int     conv_p(va_list args)
{
    void    *ptr;
    unsigned int        ptrint;

    ptr = va_arg(args, void*);
    ptrint = (unsigned int)&ptr;
    my_putstr("0x7fff");
    my_putstr(my_itoa_base_uint(ptrint, 16));

    return (1);
}

Output: 输出:

MY_PRINTF:'0x7fff505247b0'
   PRINTF:'0x7fff50524a20'

As you can see the last three char are wrong, is there any documentation about that? 如您所见,最后三个字符是错误的,是否有任何相关文档?

In the second case, you're converting the address of the variable ptr to an int , rather than its value (the pointer you're interested in). 在第二种情况下,您要将变量ptr的地址转换为int ,而不是其值(您感兴趣的指针)。

Replacing (unsigned int)&ptr; 替换(unsigned int)&ptr; with (unsigned int)ptr; (unsigned int)ptr; will give you consistent values. 将为您提供一致的价值。

And an additional aside: there's no guarantee unsigned int is large enough to represent the pointer value: you should use intptr_t or uintptr_t from <stdint.h> . 还有一个补充:不能保证unsigned int足够大以表示指针值:您应该使用<stdint.h> intptr_tuintptr_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM