我试图编写一个程序,读取用户输入的每个单词,然后将该单词粘贴到链表中。这是我到目前为止所尝试的但是遇到了seg错误但不太确定我在mallocing /指针错误的地方。 (尚未实现printList)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 20
typedef struct node{
char *word;
struct node *next;
}node_t;
node_t *read(node_t *node);
void printList(node_t *node);
node_t *insertNode(char *word, node_t *node, int size);
int main(int argc, char *argv[]) {
node_t *start = NULL;
printf("Enter a sentence:\n");
read(start);
return 0;
}
void *read(node_t *node){
int i, size = MAX_LEN;
char c, *word;
if(!(word=malloc(size))){
printf("Out of memory!\n");
exit(EXIT_FAILURE);
}
while((c=getchar())!='\n'){
for(i=0;c!=' ';i++){
word[i]=c;
if(i>size){
size=size*2;
if(!realloc(word, size)){
printf("Out of memory\n");
exit(EXIT_FAILURE);
}
}
}
node = insertNode(word,node,size);
}
return node;
}
node_t *insertNode(char *word, node_t *node, int size){
node_t *new_node, *current;
new_node = (node_t*)malloc(sizeof(node_t));
new_node->next = NULL;
if(!(new_node->word = malloc(size))){
printf("Out of memory\n");
exit(EXIT_FAILURE);
}
strcpy(new_node->word,word);
if (node == NULL){
node = new_node;
current = new_node;
}
else{
current->next = new_node;
current = new_node;
}
return node;
}