我可以只使用写函数打印存储在指针中的地址吗?(来自unistd.h lib(。
int c = 6;
void *ptr = &c;
printf("%p",ptr);
我希望使用write-not-printf获得与上面代码相同的结果。
您可以简单地将地址格式化为自己的char缓冲区,然后将其传递给write
。
通常情况下,您只需要使用sprintf
来完成此操作,但如果您不喜欢printf
,则可能也不喜欢sprintf
。
尽管如此,我将首先展示:
int c = 6;
void *ptr = &c;
char outbuf[2*sizeof(void*)+1];
sprintf("%x", p);
write(fd, outbuf, strlen(outbuf));
无sprintf
和MCVE:
#include <stdio.h>
#include <stdint.h>
int main()
{
int c = 6;
void *ptr = &c;
static const char hex_digits[]="0123456789abcdef";
size_t addr_size = sizeof (void*);
char outbuf[2*addr_size+1];
int i;
uintptr_t val =(intptr_t) ptr;
int nibble;
for (i = addr_size - 1; i >= 0; i--)
{
nibble = val % 0x10;
val /= 0x10;
outbuf[2*i+1] = hex_digits[nibble];
nibble = val % 0x10;
val /= 0x10;
outbuf[2*i] = hex_digits[nibble];
}
outbuf[2*addr_size] = 0;
printf("%sn", outbuf);
// replace with write(fd, outbuf, strlen(outbuf)) for your needs
return 0;
}