列出链接列表

时间:2010-12-08 18:45:02

标签: c

我写了一个程序。它将文本文件中的数据逐字传递到链接列表。但列出这些词语时存在问题。

#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), 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;
}

1 个答案:

答案 0 :(得分:3)

来自'man strtok':

  

使用这些时要小心   功能。如果您确实使用它们,请注意   的是:

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

所以你需要为每个单词分配新的内存,因为strtok返回的指针正在索引到行数组中。

最好通过将代码更改为:

来说明
...
  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;
...

当运行以下输入时:

check default for switches 
throw stmts to exit node

打印以下内容:

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

请注意,每行中第一个单词的指针是相同的。