我如何能转换 void *
指针 char *
,这样我就可以打印出存储在 ptr
十六进制格式的?如果没有 printf()
.
#include<stdio.h>
int main()
{
int a=5;
void *ptr=&a;
char *arr=(char*)ptr;
write(1,arr,strlen(arr));
return 0;
}
如果你没有 printf()
可用,那么你就需要手动转换数值,然后写出来。下面的例子是假设你的系统是小恩迪安的(如果是大恩迪安的,只需将你的系统中的 for
循环)。) 见 检测内隐性 更多信息。
void *ptr = &a;
unsigned char buf[sizeof(ptr)];
memcpy(buf, &ptr, sizeof(ptr));
for (int i = sizeof(ptr) - 1; i >= 0; i--) {
unsigned char hi = (buf[i] >> 4) & 0xf;
unsigned char lo = buf[i] & 0xf;
char tmp[2] = {hi, lo};
tmp[0] += hi < 10 ? '0' : 'a' - 10;
tmp[1] += lo < 10 ? '0' : 'a' - 10;
write(1, tmp, 2);
}
结果。
00007fffa6cf0f64
该 指的是 指针的类型与您要打印的值指针无关。 如果你想把一个值指针打印成一个数字(例如该值存储在&内存中的地址),你必须先把该指针转换成一个整数,这样你就可以使用数字打印的方法。 这是在 printf(3)
函数,当你指定一个指针值(不管它指向什么类型)时,用格式为 %p
格式指定器。
#include<stdio.h>
int main()
{
int a=5;
printf("The address of a is: %p\n", &a);
printf("and the value of a is: %d\n", a);
return 0;
}
在执行时,你会得到类似这样的东西。
$ pru
The address of a is: 0x7fffffffe3bc
and the value of a is: 5
$ _
你要找的函数叫做sprintf. 它以你指定的格式生成参数的文本表示(chars)。
#include<stdio.h>
#include<stdio.h>
int main()
{
int a = 5; // okay
void *ptr = &a; // okay
// conversion works only for between basic types (one number to another)
// but not for a text (human-readable hexadecimal representation)
//char *arr = (char*)ptr;
// need enough memory for storing the hexadecimal text representation including 0 value at the end, we are using 20 bytes here
char arr[20];
// write the pointer as hexadecimal
// depending on your architecture (32 bit / 64 bit), one of the following lines could work
// %x writes an unsigned int, %lx an long unsigned int
sprintf(arr, "%x", (unsigned int)ptr);
sprintf(arr, "%lx", (long unsigned int)ptr);
// some systems have the secure variant sprintf_s, where you also give the length of your array arr as parameter (here: 20) to make sure it does not write over the end
// for testing, write out the arr on screen (as %s = string)
printf("%s\n", arr);
//write(1,arr,strlen(arr));
return 0;
}