Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- char* appendCharacter(char, const char*);
- inline char* appendCharacterToMyString(char, char*);
- // I would consider this anything but memory efficient but oh well
- char* appendCharacter(char character, const char* to)
- {
- char* ret = NULL;
- size_t toLength = 0;
- size_t retLength = 0;
- if (to != NULL)
- {
- toLength = strlen(to);
- }
- retLength = toLength + 2; // Including NULL character
- ret = (char*)malloc(sizeof(char)*retLength);
- if (to != NULL)
- {
- strncpy(ret, to, toLength);
- }
- ret[retLength - 2] = character;
- ret[retLength - 1] = '\0';
- return ret;
- }
- // Just to simplify allocation and freeing of memory for our particular string (thus why it is inline)
- inline char* appendCharacterToMyString(char character, char* to)
- {
- char* ret = to;
- ret = appendCharacter(character, to);
- if (to != NULL)
- {
- free((void*)to);
- }
- return ret;
- }
- int main()
- {
- char* myStr = NULL;
- char in;
- while ((in = getchar()) != '\n')
- {
- myStr = appendCharacterToMyString(in, myStr);
- }
- printf("%s\n", myStr);
- getchar();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement