Advertisement
JamesK89

Append Character

Apr 15th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6.  
  7. char* appendCharacter(char, const char*);
  8. inline char* appendCharacterToMyString(char, char*);
  9.  
  10. // I would consider this anything but memory efficient but oh well
  11. char* appendCharacter(char character, const char* to)
  12. {
  13.     char* ret = NULL;
  14.  
  15.     size_t toLength = 0;
  16.     size_t retLength = 0;
  17.  
  18.     if (to != NULL)
  19.     {
  20.         toLength = strlen(to);
  21.     }
  22.  
  23.     retLength = toLength + 2; // Including NULL character
  24.  
  25.     ret = (char*)malloc(sizeof(char)*retLength);
  26.  
  27.     if (to != NULL)
  28.     {
  29.         strncpy(ret, to, toLength);
  30.     }
  31.    
  32.     ret[retLength - 2] = character;
  33.     ret[retLength - 1] = '\0';
  34.  
  35.     return ret;
  36. }
  37.  
  38. // Just to simplify allocation and freeing of memory for our particular string (thus why it is inline)
  39. inline char* appendCharacterToMyString(char character, char* to)
  40. {
  41.     char* ret = to;
  42.  
  43.     ret = appendCharacter(character, to);
  44.  
  45.     if (to != NULL)
  46.     {
  47.         free((void*)to);
  48.     }
  49.  
  50.     return ret;
  51. }
  52.  
  53. int main()
  54. {
  55.     char* myStr = NULL;
  56.     char in;
  57.  
  58.     while ((in = getchar()) != '\n')
  59.     {
  60.         myStr = appendCharacterToMyString(in, myStr);
  61.     }
  62.  
  63.     printf("%s\n", myStr);
  64.     getchar();
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement