fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. // Concatenates string1 and string2.
  6. // Returns the concatenated (string1+string2), or NULL on errors.
  7. // NOTE: Memory for the returned string is allocated with malloc()
  8. // by the function, so the caller is responsible to release it with
  9. // a call to free().
  10. char *StringConcat(const char *string1, const char *string2)
  11. {
  12. char *stringResult;
  13. size_t len1;
  14. size_t len2;
  15.  
  16. // Check for NULL pointers...
  17. // (Return NULL, or whatever your design is...)
  18. if (string1 == NULL || string2 == NULL) {
  19. return NULL;
  20. }
  21.  
  22. len1 = strlen(string1);
  23. len2 = strlen(string2);
  24.  
  25. // +1 for terminating NUL ('\0')
  26. stringResult = malloc(len1 + len2 + 1);
  27. if (stringResult == NULL) {
  28. return NULL; // Allocation error
  29. }
  30.  
  31. // Copy characters from first string
  32. // (exclduing the terminating NUL --> len1)
  33. memcpy(stringResult, string1, len1);
  34.  
  35. // Copy characters from second string
  36. // (including the terminating NUL --> len2+1)
  37. memcpy(stringResult + len1, string2, len2+1);
  38.  
  39. // Return destination string pointer to the caller.
  40. // NOTE: Memory must be freed by the caller calling free().
  41. return stringResult;
  42. }
  43.  
  44.  
  45. // *** TEST ***
  46. int main(void)
  47. {
  48. // Test the function
  49. char * str = StringConcat("Hello ", "World");
  50.  
  51. // Print the resulting string
  52. printf("%s\n", str);
  53.  
  54. // Don't forget to free() memory allocatd by the concat function
  55. free(str);
  56.  
  57. // All right
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 2184KB
stdin
Standard input is empty
stdout
Hello World