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 (1885B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 struct MapEntry {
      6     char *key;  /* public */
      7     int value;  /* public */
      8     struct MapEntry *__prev;
      9     struct MapEntry *__next;
     10 };
     11 
     12 struct Map {
     13    /* Attributes */
     14    struct MapEntry *__head;
     15    struct MapEntry *__tail;
     16    int __count;
     17 
     18    /* Methods */
     19    void (*put)(struct Map* self, char *key, int value);
     20    int (*get)(struct Map* self, char *key, int def);
     21    int (*size)(struct Map* self);
     22    void (*dump)(struct Map* self);
     23    void (*del)(struct Map* self);
     24 };
     25 
     26 void __Map_del(struct Map* self) {
     27     struct MapEntry *cur, *next;
     28     cur = self->__head;
     29     while(cur) {
     30         free(cur->key);
     31         /* value is just part of the struct */
     32         next = cur->__next;
     33         free(cur);
     34         cur = next;
     35     }
     36     free((void *)self);
     37 }
     38 
     39 void __Map_dump(struct Map* self)
     40 {
     41     struct MapEntry *cur;
     42     printf("Object Map count=%d\n", self->__count);
     43     for(cur = self->__head; cur != NULL ; cur = cur->__next ) {
     44          printf("  %s=%d\n", cur->key, cur->value);
     45     }
     46 }
     47 
     48 struct MapEntry* __Map_find(struct Map* self, char *key)
     49 {
     50     struct MapEntry *cur;
     51     if ( self == NULL || key == NULL ) return NULL;
     52     for(cur = self->__head; cur != NULL ; cur = cur->__next ) {
     53         if(strcmp(key, cur->key) == 0 ) return cur;
     54     }
     55     return NULL;
     56 }
     57 
     58 /* Student code will be inserted here */
     59 
     60 int main(void)
     61 {
     62     struct Map * map = Map_new();
     63     struct MapEntry *cur;
     64 
     65     /* Make sure we see all output up to an error */
     66     setvbuf(stdout, NULL, _IONBF, 0);
     67 
     68     printf("Map test\n");
     69     map->put(map, "z", 8);
     70     map->put(map, "z", 1);
     71     map->put(map, "y", 2);
     72     map->put(map, "b", 3);
     73     map->put(map, "a", 4);
     74     map->dump(map);
     75 
     76     printf("size=%d\n", map->size(map));
     77 
     78     printf("z=%d\n", map->get(map, "z", 42));
     79     printf("x=%d\n", map->get(map, "x", 42));
     80 
     81     map->del(map);
     82 }