#include #include #include typedef struct { char *text; size_t capacity; size_t size; } String; void init_string(String *str) { str->text = NULL; str->size = 0; str->capacity = 0; } int init_string_by_literal(String *dest, const char *src) { dest->size = dest->capacity = strlen(src)+1; dest->text = (char*)malloc(dest->capacity); if (dest->text == NULL) { init_string(dest); return 1; } strcpy(dest->text, src); return 0; } void destroy_string(String *str) { free(str->text); init_string(str); } int append_string(String *dest, String src) { if (src.size == 0) { return 0; } if (dest->text == NULL) { dest->text = (char*)malloc(src.capacity); strcpy(dest->text, src.text); dest->capacity = src.capacity; dest->size = src.size; return 0; } dest->size += src.size-1; if (dest->size > dest->capacity) { do { dest->capacity <<= 1; } while(dest->capacity < dest->size); dest->text = realloc(dest->text, dest->capacity); if (dest->text == NULL) { return 1; } } strcat(dest->text, src.text); return 0; } int main() { String s1, s2, s3; if (init_string_by_literal(&s1, "Pera") != 0) { printf("Failed to init s1\n"); return 1; } if (init_string_by_literal(&s2, ", ") != 0) { printf("Failed to init s2\n"); return 2; } if (init_string_by_literal(&s3, "Mika") != 0) { printf("Failed to init s3\n"); return 3; } if (append_string(&s1, s2) != 0) { printf("Failed to append s2 to s1\n"); return 4; } if (append_string(&s1, s3) != 0) { printf("Failed to append s3 to s1\n"); return 5; } printf("The resulting string is \"%s\"\n", s1.text); destroy_string(&s1); destroy_string(&s2); destroy_string(&s3); return 0; }