gpt4 book ai didi

c - 列出链表

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:38 25 4
gpt4 key购买 nike

我写了一个程序。它逐字地将文本文件中的数据提取到链表中。但是在列出单词时存在问题。

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

最佳答案

来自'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.

所以你需要为每个单词分配新的内存,因为 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

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

关于c - 列出链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4391037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com