fork download
  1. #include <stdio.h> /* For printf() */
  2. #include <stdlib.h> /* For malloc(), free() */
  3. #include <string.h> /* For strcat(), strlen() */
  4.  
  5.  
  6. /*
  7.  * Concatenates input strings into a single string.
  8.  * Returns the pointer to the resulting string.
  9.  * The string memory is allocated with malloc(),
  10.  * so the caller must release it using free().
  11.  * The input string array must have NULL as last element.
  12.  * If the input string array pointer is NULL,
  13.  * NULL is returned.
  14.  * On memory allocation error, NULL is returned.
  15.  */
  16. char * ConcatenateStrings(const char** strings)
  17. {
  18. int i = 0; /* Loop index */
  19. int count = 0; /* Count of input strings */
  20. char * result = NULL; /* Result string */
  21. int totalLength = 0; /* Length of result string */
  22.  
  23.  
  24. /* Check special case of NULL input pointer. */
  25. if (strings == NULL)
  26. {
  27. return NULL;
  28. }
  29.  
  30. /*
  31.   * Iterate through the input string array,
  32.   * calculating total required length for destination string.
  33.   * Get the total string count, too.
  34.   */
  35. while (strings[i] != NULL)
  36. {
  37. totalLength += strlen(strings[i]);
  38. i++;
  39. }
  40. count = i;
  41. totalLength++; /* Consider NUL terminator. */
  42.  
  43. /*
  44.   * Allocate memory for the destination string.
  45.   */
  46. result = malloc(sizeof(char) * totalLength);
  47. if (result == NULL)
  48. {
  49. /* Memory allocation failed. */
  50. return NULL;
  51. }
  52.  
  53. /*
  54.   * Concatenate the input strings.
  55.   */
  56. for (i = 0; i < count; i++)
  57. {
  58. strcat(result, strings[i]);
  59. }
  60.  
  61. return result;
  62. }
  63.  
  64. /*
  65.  * Tests the string concatenation function.
  66.  */
  67. int main(void)
  68. {
  69. /* Result of string concatenation */
  70. char * result = NULL;
  71.  
  72. /* Some test string array */
  73. const char * test[] =
  74. {
  75. "Hello ",
  76. "world",
  77. "!",
  78. " ",
  79. "Ciao ",
  80. "mondo!",
  81. NULL /* String array terminator */
  82. };
  83.  
  84. /* Try string concatenation code. */
  85. result = ConcatenateStrings(test);
  86.  
  87. /* Print result. */
  88. printf("%s\n", result);
  89.  
  90. /* Release memory allocated by the concatenate function. */
  91. free(result);
  92.  
  93. /* All right */
  94. return 0;
  95. }
  96.  
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
Hello world! Ciao mondo!