/*
    demonstrate how a string with multiple works (called tokens)
    can be broken into the individual tokens 

    strsep modifies the given string by replacing delimiters w/NULL
    it then returns a pointer to the start of the string

*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

int main()
{
    char *line = 0;
    size_t size;
    size_t bytes_read;

    printf("Enter string of tokens: ");
    bytes_read = getline(&line, &size, stdin);

    printf("address of line = %x\n", (void *) line);

    char *line_ptr = line;
    char *delimiters = " \t\n"; // need all three 
    char *token;

    int i;
    for (i = 0; token = strsep(&line_ptr, delimiters); )
    {
        // skip empty strings
        if (token[0] == 0)
            continue;
        printf("token[%d] = %s", i, token);
        printf("\taddress = %x", token);

        // if we wanted to allocate memory to use outside of this
        // function, we could allocate new memory for the token
        char *token_copy = strdup(token);

        printf("\n");

        // WARNING: token is a pointer into the string line
        //          if you plan to use it in other parts of the
        //          program you need to make sure you manage the memory
        //          correctly

        i++;
    }

    // WARNING: this deletes the memory used by all the tokens 
    free(line);
}

