spikeysnack

CONCAT

Nov 19th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4.  
  5. /** concatenate strings without limit  */
  6.  
  7. #define max_concat 256
  8.  
  9. /* concatenate */
  10. #define CONCAT(...)   ( __extension__ ({                        \
  11.   char* sarray[] = { __VA_ARGS__ , NULL };                      \
  12.   char* out =  calloc(max_concat, sizeof(char));                \
  13.   do { size_t n = 0;                                            \
  14.   while (sarray[n] != NULL)                                     \
  15.     { sprintf( out, "%s%s", out, sarray[n] ); n++; }            \
  16.   }while(0);                                                    \
  17.   out = realloc(out, strlen(out)+1);                            \
  18. }))
  19.  
  20.  
  21.  
  22. int main( int argc, char** argv, char** env)
  23. {
  24.   char* str = CONCAT( "dog", "cat", "horse", "butt", "smacker", " - ", "SNAP", "!" );
  25.   fprintf(stdout, "%s\n" , str);
  26.   free (str);
  27.   return 0;
  28. }
  29.  
  30. /** NOTES
  31. *   the ( __extension__({  and  subsequent  }))
  32. *   enclose the macro as a gnu extension so that
  33. *   it is not flagged as a warning in pedantic mode.
  34. *   It also creates a scope where statically allocated
  35. *   variables can be created and disposed of at the "return".
  36. *  
  37. *  The last statement is what the macro "returns", in this case
  38. *  the dynamically allocated string (out). The realloc command
  39. *  is not really needed but right-sizes the string. It still must
  40. *  be freed later.
  41. */
Add Comment
Please, Sign In to add comment