learning-cc4e

Solution to https://cc4e.com/. If you copy these you're not right in the head.
git clone https://kaka.farm/~git/learning-cc4e
Log | Files | Refs

main.c (1160B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 
      4 struct pystr
      5 {
      6     int length;
      7     int alloc; /* the length of *data */
      8     char *data;
      9 };
     10 
     11 /* Constructor - x = str() */
     12 struct pystr * pystr_new() {
     13     struct pystr *p = malloc(sizeof(*p));
     14     p->length = 0;
     15     p->alloc = 10;
     16     p->data = malloc(10);
     17     p->data[0] = '\0';
     18     return p;
     19 }
     20 
     21 /* Destructor - del(x) */
     22 void pystr_del(const struct pystr* self) {
     23     free((void *)self->data); /* free string first */
     24     free((void *)self);
     25 }
     26 
     27 void pystr_dump(const struct pystr* self)
     28 {
     29     printf("Pystr length=%d alloc=%d data=%s\n",
     30             self->length, self->alloc, self->data);
     31 }
     32 
     33 int pystr_len(const struct pystr* self)
     34 {
     35     return self->length;
     36 }
     37 
     38 char *pystr_str(const struct pystr* self)
     39 {
     40     return self->data;
     41 }
     42 
     43 
     44 int main(void)
     45 {
     46     setvbuf(stdout, NULL, _IONBF, 0);  /* Internal */
     47 
     48     struct pystr * x = pystr_new();
     49     pystr_dump(x);
     50 
     51     pystr_append(x, 'H');
     52     pystr_dump(x);
     53 
     54     pystr_appends(x, "ello world");
     55     pystr_dump(x);
     56 
     57     pystr_assign(x, "A completely new string");
     58     printf("String = %s\n", pystr_str(x));
     59     printf("Length = %d\n", pystr_len(x));
     60     pystr_del(x);
     61 }