Search code examples
clinked-listtokenize

Linked List not working with strtok


This is what I am intending to do: Get the contents of a webpage, break it into pieces using strtok and storing each piece in a node of a linked list, then take each of these nodes and use strtok to break them apart further, and get the pieces of data I want out of them. The problem I am having is that for some reason, my linked list gets reduced to one node when I start using strtok for the second time.

linked list node struct:

struct node {
  char* tidbit;
  char* address[35];
  char* key[51];
  struct node *next;
};

code that builds the linked list:

root = malloc(sizeof(struct node));
conductor = root;
root -> next = malloc(sizeof(struct node));

conductor->tidbit = strtok(buf,"+"); // sets the tidbit variable equal to the result of strtok


// builds the linked list of items
while (conductor->tidbit!= NULL){
      conductor -> next = malloc(sizeof(struct node));
      conductor = conductor-> next;
      conductor->tidbit = strtok(NULL, "+");
}
conductor->next = NULL;

This code works, and returns the entire list:

conductor = root;
while (conductor->next != NULL){
    i++;
    printf("Next %d: %s\n", i, conductor->tidbit);
    conductor = conductor ->next;
}

This code only returns the first item entered into the list (the extra next is because the first item on the linked list is junk data and I don't need it).

    conductor = root;
    conductor = conductor->next;

    while (conductor->next != NULL){
            conductor = conductor->next;
            strtok(conductor->tidbit, ">");
            strtok(NULL, ">");
            conductor->tidbit = strtok(NULL, ">");
            strncpy(conductor->key, conductor->tidbit, 51);
            conductor->key[51] = '\0';
            conductor->tidbit = strtok(NULL, ">");
            strncpy(conductor->address, conductor->tidbit + 42, 34);
            if (conductor->address[33] == '"')
                conductor->address[33] = '\0';
            else
                conductor->address[34] = '\0';
            printf("Values: key: %s address: %s\n", conductor->key, conductor->address);
            while (strtok(NULL, ">") != NULL){
            }
    }

Essentially this last piece of code is trying to take the string returned by the first use of strtok, and break it down into pieces delimited by ">". The it pulls two relevant pieces of data (address and key) from the string, storing them with the node. Then it should go to the next node and do it again until it runs out of nodes.

I have a hunch that it is strtok that is causing problems. The sections are in variable lengths, but always a set distance from a certain character (">") which is why I need strtok. Any advice is appreciated.


Solution

  • I'd start with the simple problem that char* address[35] declares an array of 35 char*; not an array of 35 char. The rest should be blatantly obvious once you fix that. The same goes for char *key[51]; – WhozCraig