Search code examples
cpointersprintfvariadic-functions

How do you manipulate a void pointer passed as a parameter in a variadic function in C


I have the following variadic function (a version of vsprintf):

buf[size] = '0'; size++;                
buf[size] = 'x'; size++;
void **ptr = va_arg(arg, void *);
num = unsigned_to_base(&buf[size], bufsize, (int)*ptr, HEX_BASE, 8);

where the function unsigned_to_base() takes in a hexadecimal number and places it as a string in buf (the 0x prefix must be placed manually as the function doesn't automatically. unsigned_to_base functions as follows:

int unsigned_to_base(char *buf, size_t bufsize, unsigned int val, int base, int min_width) where buf is the destination, bufsize is the size of buf, val is the value in question, base is the base number system to express the string as (in this case it is base 16, hex), and min_width is the minimum width of the output string, padding the front with leading 0s if needed. The function returns the number of characters written to buf.

The parameter I am extracting in the variadic function is (void *) 0x20200004 and I am trying to return "0x20200004". However, the actual return value I am receiving is "0x00012000". What am I doing wrong?

Thanks!


Solution

  • va_arg returns a value of the type given as a parameter. Your va_arg returns a void*, but you're storing it in a void**, which I don't think is what you want. Also, I see you have the C++ tag, so why are you using variadic lists in C++ anyway?