C语言 在 C 中打印 void* 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15292237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing a void* variable in C
提问by sharkbait
Hi all I want to do a debug with printf. But I don't know how to print the "out" variable.
大家好,我想用 printf 进行调试。但我不知道如何打印“out”变量。
Before the return, I want to print this value, but its type is void* .
在返回之前,我想打印这个值,但它的类型是 void* 。
int
hexstr2raw(char *in, void *out) {
char c;
uint32_t i = 0;
uint8_t *b = (uint8_t*) out;
while ((c = in[i]) != 'printf("%p\n", out);
') {
uint8_t v;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'A' && c <= 'F') {
v = 10 + c - 'A';
} else if (c >= 'a' || c <= 'f') {
v = 10 + c - 'a';
} else {
return -1;
}
if (i%2 == 0) {
b[i/2] = (v << 4);
printf("c='%c' \t v='%u' \t b[i/2]='%u' \t i='%u'\n", c,v ,b[i/2], i);}
else {
b[i/2] |= v;
printf("c='%c' \t v='%u' \t b[i/2]='%u' \t i='%u'\n", c,v ,b[i/2], i);}
i++;
}
printf("%s\n", out);
return i;
}
How can I do? Thanks.
我能怎么做?谢谢。
回答by Graham Borland
uint8_t *b = (uint8_t*) out;
is the correct way to print a (void*)pointer.
是打印(void*)指针的正确方法。
回答by unwind
This:
这个:
int j;
for(j = 0; j < i; ++j)
printf("%02x\n", ((uint8_t*) out)[j]);
implies that outis in fact a pointer to uint8_t, so perhaps you want to print the data that's actually there. Also note that you don't need to cast from void *in C, so the cast is really pointless.
暗示这out实际上是一个指向 的指针uint8_t,所以也许您想打印实际存在的数据。另请注意,您不需要void *在 C 中进行转换,因此转换确实毫无意义。
The code seems to be doing hex to binary conversion, storing the results at out. You can print the igenerated bytes by doing:
代码似乎在进行十六进制到二进制的转换,将结果存储在out. 您可以i通过执行以下操作打印生成的字节:
The pointer valueitself is rarely interesting, but you can print it with printf("%p\n", out);. The %pformatting specifier is for void *.
该指针值本身很少是有趣的,但你可以用它打印printf("%p\n", out);。该%p格式说明符是void *。
回答by dasblinkenlight
The format specifier for printing void pointers using printfin C is %p. What usually gets printed is a hexadecimal representation of the pointer (although the standard says simply that it is an implementation defined character sequence defining a pointer).
printf在 C 中使用的打印空指针的格式说明符是%p. 通常打印的是指针的十六进制表示(尽管标准简单地说它是定义指针的实现定义的字符序列)。

