Home > Mobile >  How to write a variadic function in C that takes integers and returns them all together in a dynamic
How to write a variadic function in C that takes integers and returns them all together in a dynamic

Time:03-20

For example:

char* function(int n, ...); //prototype
main()
{
 char* s;
 s= function(3, 123, 456, 789);
 printf("%s", s);
}

How do i write this function that will take integers and return a dynamic string of these integers? While trying to solve this, I have came across function itoa(); but I couldn't find enough things about it and there were very few examples using it, and also, should I dynamically allocate a character string in C and since (at least I think this is how it goes) I will be putting those integers in order one by one, should I use realloc for that string because its size will get bigger and bigger until im done? Do I use strcat to make basically a string of strings? And probably my biggest question, when and how in all that mess do I use function itoa()? Function should return

"123456789"

CodePudding user response:

C Algorithm

  1. Determine worse cast size buffer for one int. Hint: As text, how long is INT_MIN?

  2. Allocate a buffer that is n*worst_case 1.

  3. Set buf[0] = '\0';, size_t length_used = 0;

  4. Walk the variadic arguments with va_start(), va_arg(), va_end() and friends. One at a time, convert using sprintf() into the end of the used buffer. Use the return value of the sprintf() to keep track of how far the used portion of the buffer has grown.

  5. Perform a final realloc() to shrink and right-size the allocated buffer if desired.

  6. Code code checks for errors in allocation and printing.

  7. Take a walk and enjoy the week-end as spring is coming. (or maybe autumn?)


strcat() not needed.

itoa() not needed.


Advanced

To determine the bit width of value bits in an int (even if it has padding) use IMAX_BITS(INT_MAX).

To find the number of decimal digits given the bit width:

// bit_width * log2(10) rounded up
IMAX_BITS(m)*28/93   1

Account for the '-'.

  • Related