cdynamic-memory-allocationvariadic-functionsstring.hitoa

How to write a variadic function in C that takes integers and returns them all together in a dynamic string?


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"

EDIT: Thank you all for help, I took into consideration everything said and managed to solve this problem. Here is my final code (probably could have done a better job about memory management):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

char * function(int n, ...);

int main()
{
    char* s;
  s = function(3, 123, 456, 789);
  printf("%s", s);
  free(s);
  s=function(9, 123,456,789,123,789, 12, 433, 553, 341);
  printf("\n%s", s);
  return 0;
}
char * function(int n, ...)
{
    char str[100]={0};
    char* res=0;
    int i, br;
  va_list args;
  va_start(args, n);

  for (i = 0; i < n; i++)
  {
      br=va_arg(args, int);
      itoa(br, str, 10);
      char* tmp=(char *)malloc(sizeof(str));
      strcpy(tmp, res ? res : "");
      strcat(tmp, str);
      free(res);
      res=tmp;
  }
  va_end(args);
  return res;
}

Solution

  • 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 '-'.