简体   繁体   English

在C中打印void *变量

[英]Printing a void* variable in C

Hi all I want to do a debug with printf. 大家好我想用printf进行调试。 But I don't know how to print the "out" variable. 但我不知道如何打印“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]) != '\0') {
        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. 谢谢。

printf("%p\n", out);

是打印(void*)指针的正确方法。

This: 这个:

uint8_t *b = (uint8_t*) out;

implies that out is in fact a pointer to uint8_t , so perhaps you want to print the data that's actually there. 暗示out实际上是指向uint8_t ,所以也许你想要打印实际存在的数据。 Also note that you don't need to cast from void * in C, so the cast is really pointless. 另请注意,您不需要在C中使用void *进行强制转换,因此强制转换非常无意义。

The code seems to be doing hex to binary conversion, storing the results at out . 代码似乎是进行十六进制到二进制转换,将结果存储out You can print the i generated bytes by doing: 您可以通过执行以下操作打印i生成的字节:

int j;
for(j = 0; j < i; ++j)
  printf("%02x\n", ((uint8_t*) out)[j]);

The pointer value itself is rarely interesting, but you can print it with printf("%p\\n", out); 指针值本身很少有趣,但您可以使用printf("%p\\n", out);打印它printf("%p\\n", out); . The %p formatting specifier is for void * . %p格式说明符用于void *

The format specifier for printing void pointers using printf in C is %p . 在C中使用printf打印void指针的格式说明符是%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). 通常打印的是指针的十六进制表示(尽管标准简单地说它是定义指针​​的实现定义的字符序列)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM