• wordstats.c

  • §

    Jonas Altrock ew20b126@technikum-wien.at

    To overview.

    The whole source file wordstats.c.

    /* compile with `clang -std=c99 -Wall -o wordstats wordstats.c` */
  • §

    Include C-libraries for input/output, allocation of memory, string manipulation, and the bool type.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdbool.h>
  • §

    Task

  • §

    Implement a tool for word statistics. For this, your program should allow the user to enter an arbitrary number of words with up to 63 characters. For each word it should be checked whether it already existed and if not, it should be stored. After “.” was entered, the program should print the number of distinct words that were entered and then terminate.

    Solution

  • §
    int main() {
  • §

    We store the words in a table of strings. Initially, the table has space for 16 and contains 0 entries. calloc takes the number of elements and the size of one element, and fills a dynamic memory region of the correct size with 0.

        int size = 16;
        char **table = calloc(size, sizeof(char*));
        int words = 0;
  • §

    One word can be up to 63 characters plus 1 for null-termination.

        char *buffer = calloc(64, sizeof(char));
  • §

    Read in words in a loop.

        do {
  • §

    Read a string into the buffer.

            scanf("%s", buffer);
  • §

    End program if it is “.”

            if (strcmp(".", buffer) == 0) {
                break;
            }
  • §

    Search for the word in the table.

            bool found = false;
    
    
            for (int i = 0; i < words; i++) {
                if (strcmp(buffer, table[i]) == 0) {
                    found = true;
                    break;
                }
            }
  • §

    If it was not found, add it.

            if (!found) {
  • §

    If adding it would overflow the table, double table capacity.

                if (words == size) {
                    size *= 2;
                    table = realloc(table, size * sizeof(char*));
                }
  • §

    Store a duplication of the buffer in the table.

                table[words] = strdup(buffer);
                words += 1;
            }
        } while(1);
  • §

    Print the result: the count of unique words.

        printf("%i", words);
  • §

    Now clean up all the dynamic memory allocations.

        for (int i = 0; i < words; i++) {
            free(table[i]);
            table[i] = NULL;
        }
    
        free(table);
        table = NULL;
    
        free(buffer);
        buffer = NULL;
    
        return 0;
    }