#include #include #include #include "04-MyString.h" // The only code that needs to know about the internals of a // MyString is the code in this file implementing MyString typedef struct myString_t { int length; char *str; } * MyString; // takes a null terminated array of char as the argument MyString MyString_create(const char * cstring) { MyString result = malloc(sizeof(*result)); if ( result == NULL ) return NULL; if (cstring == NULL ) { result->length = 0; result->str = NULL; return result; } result->str = malloc(strlen(cstring)); if ( result->str == NULL ) { free(result); return NULL; } result->length = strlen(cstring); memcpy(result->str, cstring, result->length); // don't copy '\0' return result; } // deep copy - takes another MyString as the argument bool MyString_copy(MyString dest, const MyString src) { if ( src == NULL || dest == NULL ) return false; // if malloc() fails here, we want dest to be unchanged char *strcopy = malloc(sizeof(char) * src->length); if ( strcopy == NULL ) return false; if ( dest->str != NULL ) free(dest->str); memcpy(strcopy, src->str, src->length); dest->str = strcopy; dest->length = src->length; return true; } void MyString_print(MyString s) { if ( s == NULL ) return; printf("(%d) ", s->length); for ( int i = 0; i < s->length; i++ ) { putchar(s->str[i]); } putchar('\n'); }