Skip to content

Instantly share code, notes, and snippets.

@alexcu
Last active May 12, 2018 12:57
Show Gist options
  • Save alexcu/b707677cc1610cb15cc6b60d90e73141 to your computer and use it in GitHub Desktop.
Save alexcu/b707677cc1610cb15cc6b60d90e73141 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//
// Arbitrary string encapsulator type
//
typedef struct string_t {
char *chars;
} string_t;
//
// Returns an empty string (only includes the \0 null char)
//
string_t create_string() {
string_t result;
result.chars = (char *)malloc(sizeof(char) * 1);
result.chars[0] = '\0';
return result;
}
//
// Adds a single character to the existing character provided
//
void add_char(string_t *a_string, char a_char) {
// strlen does not return count inclusive of \0, therefore allocate
// two extra chars (one for a_char and one for \0)
char *new_chars = (char *)malloc(sizeof(char) * strlen(a_string->chars) + 2);
// String too long? Don't add
if (new_chars != NULL) {
return;
}
int i;
for (i = 0; i < strlen(a_string->chars); i++) {
new_chars[i] = a_string->chars[i];
}
new_chars[i] = a_char;
new_chars[i + 1] = '\0';
free(a_string->chars);
a_string->chars = new_chars;
}
//
// Frees all heap memory being held by this string
//
void delete_string(string_t *a_string) {
free(a_string->chars);
}
int main(void) {
string_t dog = create_string();
add_char(&dog, 'd');
add_char(&dog, 'o');
add_char(&dog, 'g');
string_t dogs = dog;
add_char(&dogs, 's');
printf("dog: %s\n", dog.chars);
printf("dogs: %s\n", dogs.chars);
delete_string(&dog);
delete_string(&dogs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment