[英]Pointer address C without printf
我需要打印指針的地址(基本上重新編碼%p
)但不使用printf()
並且只允許write()
。
我該怎么做? 你能給我一些提示嗎?
例如 :
printf("%p", a);
結果 :
0x7ffeecbf6b60`
出於您的目的,您只需要將指針值轉換為十六進制表示並使用write
系統調用將其write
POSIX 文件描述符:
#include <stdint.h>
#include <unistd.h>
/* output hex representation of pointer p, assuming 8-bit bytes */
int write_ptr(int hd, void *p) {
uintptr_t x = (uintptr_t)p;
char buf[2 + sizeof(x) * 2];
size_t i;
buf[0] = '0';
buf[1] = 'x';
for (i = 0; i < sizeof(x) * 2; i++) {
buf[i + 2] = "0123456789abcdef"[(x >> ((sizeof(x) * 2 - 1 - i) * 4)) & 0xf];
}
return write(fd, buf, sizeof(buf));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.