[英]Linked-List: read String in C
I need to read string (line by line) from a file and store them to linked list. 我需要从文件中读取字符串(逐行)并将其存储到链接列表中。 I can read from file and print them. 我可以从文件中读取并打印它们。 However, I have issue how to store them to linked list. 但是,我有问题如何将它们存储到链接列表。 I tried to create linked-list and save them like below: 我试图创建链接列表并将其保存如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data[256];
struct node *next;
} node_t;
node_t *head = NULL;
node_t *current = NULL;
int main(int argc, char const *argv[])
{
char temp = 'Hello';
insertToHead(temp);
return 0;
}
void insertToHead(char *word)
{
node_t *link = (node_t *) malloc(sizeof(node_t));
link->data = strcpy(link->data , word);
link->next = head;
head = link;
}
There are many issues. 有很多问题。
I fixed the here and now the program compiles at least: 我修复了这里,现在程序至少可以编译:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char data[256];
struct node *next;
} node_t;
node_t *head = NULL;
node_t *current = NULL;
void insertToHead(char *word)
{
node_t *link = (node_t *) malloc(sizeof(node_t));
strcpy(link->data , word);
link->next = head;
head = link;
}
int main(int argc, char const *argv[])
{
char *temp = "Hello";
insertToHead(temp);
return 0;
}
You really should learn how to read the output of your compiler. 您确实应该学习如何读取编译器的输出。
There were quite a few syntactic problems and you should include the string library: 有很多语法问题,您应该包括字符串库:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char data[256];
struct node *next;
} node_t;
node_t *head = NULL;
node_t *current = NULL;
void insertToHead(char *word) {
node_t *link = (node_t *) malloc(sizeof(node_t));
strcpy(link->data , word);
link->next = head;
head = link;
}
int main(int argc, char const *argv[]) {
char *temp = "Hello";
insertToHead(temp);
return 0;
}
EDIT 编辑
I was trying to solve the issue when @MichaelWalz already posted the solution @MichaelWalz已发布解决方案时,我正在尝试解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.