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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.