Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. void JoinStrings(char* ppszSourceStringArray[],
  6. int nSourceStringArrayLength, char** ppszOutput,
  7. int *pnOutputLength) {
  8. if (ppszSourceStringArray == NULL) {
  9. return;
  10. }
  11.  
  12. if (nSourceStringArrayLength <= 0) {
  13. return;
  14. }
  15.  
  16. if (ppszOutput == NULL) {
  17. return;
  18. }
  19.  
  20. if (pnOutputLength == NULL) {
  21. return;
  22. }
  23.  
  24. int nTotalBytes = 0;
  25. for(int i = 0;i < nSourceStringArrayLength;i++) {
  26. const int CURRENT_ENTRY_SIZE
  27. = strlen(ppszSourceStringArray[i]) + 1;
  28. nTotalBytes += CURRENT_ENTRY_SIZE;
  29. *ppszOutput = (char*)realloc(*ppszOutput,
  30. (nTotalBytes)*sizeof(char));
  31. if (i == 0) {
  32. memset(*ppszOutput, 0, nTotalBytes);
  33. }
  34. strcat(*ppszOutput, ppszSourceStringArray[i]);
  35. }
  36. const int FINISHED_STRING_SIZE = strlen(*ppszOutput) + 1;
  37. *ppszOutput = (char*)realloc(*ppszOutput,
  38. (FINISHED_STRING_SIZE)*sizeof(char));
  39. (*ppszOutput)[FINISHED_STRING_SIZE - 1] = '\0';
  40. *pnOutputLength = FINISHED_STRING_SIZE;
  41. }
  42.  
  43. int main() {
  44. const int NUM_STRINGS = 6;
  45.  
  46. char* strings[] = {
  47. "Now is the time for all good men ",
  48. "to come to the aid of ",
  49. "their country.\nAnd to the Republic ",
  50. "for which it stands, ",
  51. "one nation, under God, indivisible, with liberty ",
  52. "and justice for all.\n"
  53. };
  54.  
  55. int nOutputLength = 0;
  56. char *pszOutput = NULL;
  57. JoinStrings(strings, NUM_STRINGS, &pszOutput, &nOutputLength);
  58.  
  59. printf(pszOutput);
  60.  
  61. free(pszOutput);
  62. pszOutput = NULL;
  63.  
  64. memset(strings, 0, NUM_STRINGS);
  65.  
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement