fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct {
  6. char *str;
  7. } StringBuilder;
  8.  
  9. void append(StringBuilder *sb, const char *str) {
  10. if (!str) return;
  11.  
  12. const size_t len = sb->str ? strlen(sb->str) : 0;
  13. char *newstr = (char *) realloc(sb->str, len + strlen(str) + 1);
  14. if (newstr) {
  15. sb->str = newstr;
  16. strcpy(newstr + len, str);
  17. }
  18. }
  19.  
  20. void setLength(StringBuilder *sb, size_t n) {
  21. char *newstr = (char *) realloc(sb->str, n + 1);
  22. if (newstr) {
  23. sb->str = newstr;
  24. sb->str[n] = '\0';
  25. }
  26. }
  27.  
  28. int main() {
  29. StringBuilder sb = { .str = 0 };
  30. append(&sb, "Привет америкосам");
  31. printf("%s\n", sb.str);
  32. append(&sb, ", я вас уделаю!");
  33. printf("%s\n", sb.str);
  34. setLength(&sb, 2);
  35. printf("%s\n", sb.str);
  36. setLength(&sb, 0);
  37. printf("%s\n", sb.str);
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0s 9416KB
stdin
Standard input is empty
stdout
Привет америкосам
Привет америкосам, я вас уделаю!
П