我可以僅使用寫入功能列印存盤在指標中的地址嗎?(來自 unistd.h 庫)。
int c = 6;
void *ptr = &c;
printf("%p",ptr);
我想使用 write not printf 獲得與上面代碼相??同的結果。
uj5u.com熱心網友回復:
您可以簡單地將地址格式化為自己的字符緩沖區并將其傳遞給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("%s\n", outbuf);
// replace with write(fd, outbuf, strlen(outbuf)) for your needs
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519691.html
標籤:C指针记忆内存地址
