Printing a void* variable in C

南笙酒味 提交于 2019-12-03 08:44:31

问题


Hi all I want to do a debug with printf. But I don't know how to print the "out" variable.

Before the return, I want to print this value, but its type is 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.


回答1:


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. Also note that you don't need to cast from void * in C, so the cast is really pointless.

The code seems to be doing hex to binary conversion, storing the results at out. You can print the i generated bytes by doing:

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);. The %p formatting specifier is for void *.




回答2:


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

is the correct way to print a (void*) pointer.




回答3:


The format specifier for printing void pointers using printf in 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).



来源:https://stackoverflow.com/questions/15292237/printing-a-void-variable-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!