开发者

Listing a linked list

I wrote a program. It takes data from a text file to a linked list word by word. But there is a problem at listing the words.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct list
{
    char *data;
    struct list *next;
} node;

int main()
{
    int i;
    char *word = NULL;
    char line[1000];
    node *root,*temp;

    root = (node *) malloc(sizeof(node));
    temp = root;
    FILE *f = fopen("test.txt","r");
    while (fgets( line, sizeof(line)开发者_JAVA百科, f ))
        for (word = strtok(line, " "); word; word = strtok(NULL, " "))
        {
            temp->data = word;
            temp->next=(node *) malloc(sizeof(node));
            temp=temp->next;
        }
    fclose(f);
    temp =root;
    for(i=0; i<10; i++)
    {
        printf("%s\n",temp->data);
        temp=temp->next;
    }
    return 0;
}


From 'man strtok':

Be cautious when using these functions. If you do use them, note that:

   * These functions modify their first argument.
   * These functions cannot be used on constant strings.
   * The identity of the delimiting character is lost.

So you need to allocate new memory for each word because the pointers returned by strtok are indexing into the line array.

This is best illustrated by changing the code to:

...
  while (fgets( line, sizeof(line), f )) {
    printf("%s\n",line);
    for (word = strtok(line, " "); word; word = strtok(NULL, " ")) {
      printf("%p\n",word);
      temp->data = word;
...

Which when run on the following input:

check default for switches 
throw stmts to exit node

prints the following:

check default for switches

0x7fff94e0bf70
0x7fff94e0bf76
0x7fff94e0bf7e
0x7fff94e0bf82
throw stmts to exit node

0x7fff94e0bf70
0x7fff94e0bf76
0x7fff94e0bf7c
0x7fff94e0bf7f
0x7fff94e0bf84
throw
stmts

t
throw
stmts
to
exit
node

Notice that the pointer for the first word in each line is the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜