Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a void* variable in C

Tags:

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.

like image 505
sharkbait Avatar asked Mar 08 '13 10:03

sharkbait


People also ask

How do I print void data?

printf("size of void pointer = %d\n\n",sizeof(ptr)); //size of integer pointer. printf("size of integer pointer = %d\n\n",sizeof(p));

What does void * func () mean?

Void functions, also called nonvalue-returning functions, are used just like value-returning functions except void return types do not return a value when the function is executed. The void function accomplishes its task and then returns control to the caller. The void function call is a stand-alone statement.

Can a variable be void in C?

C # in Telugu The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

Can we dereference a void pointer?

Some Interesting Facts: 1) void pointers cannot be dereferenced. For example the following program doesn't compile.


2 Answers

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

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

like image 153
Graham Borland Avatar answered Sep 24 '22 11:09

Graham Borland


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 *.

like image 25
unwind Avatar answered Sep 20 '22 11:09

unwind