c - 将 char 数组添加到链表
问题描述
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
char word[20];
struct node * next;
}node;
int main(){
FILE *ifp;
char newword[20];
node * head;
ifp = fopen("para.txt","r");
head = (node * )malloc(sizeof(node));
while(fscanf(ifp,"%s",newword) != EOF){
head -> next = NULL;
head -> word = newword;
}
return 0;
}
我想将文本文件读取的单词添加到链接列表中。我试图用这段代码做,但我做不到。我怎样才能解决这个问题。
解决方案
您只需分配一个节点 ( head
),然后在循环的每次迭代中更改其内容。要创建一个链表,您需要node
为每个单词分配一个新的(循环的每次迭代)。这样的事情应该这样做:
int main(){
FILE *ifp;
char newword[20];
node * head = NULL;
node *last = NULL;
node *current;
ifp = fopen("para.txt","r");
if (ifp == NULL) {
fprintf(stderr, "Unable to open file para.txt\n");
return EXIT_FAILURE;
}
while(fscanf(ifp,"%19s",newword) != EOF){
current = malloc(sizeof(node));
strcpy(current -> word,newword);
if(last) {
last->next = current;
}
else {
head = current;
}
last = current;
}
return EXIT_SUCCESS;
}
推荐阅读
- javascript - 下面的代码是异步的吗?
- ios - 在 Xcode 10 中设置状态栏样式
- java - 如何从属性名称中给出的json中读取属性值
- caching - 如何在 .net-core-2.1 中使用内存缓存避免缓存未命中
- mysql - 使用 mySql 的简单 React 无法读取表记录
- c# - 在多个构造函数参数中注入具有相同接口的不同实现
- powershell - 在 PowerShell 中从 CNAME 解析主机名
- javascript - 阻止用户从嵌入的 YouTube 视频中获取 url/禁用剪贴板
- sql - Entity Framework 生成的 SQL 运行速度极慢
- web-scraping - 从延迟加载的视频中抓取视频链接