我正在尝试编写一个函数words
,该函数从作为参数传递的文本中生成一个单词的单链表(由空格分隔的字符序列)。结果列表中的单词应与文本中的相同。
不幸的是,程序在运行时出错,你能解释一下出了什么问题,我也很感激一些提示。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
struct node{
char* word;
struct node* next;
};
void printList(struct node* list){
struct node* it = list;
while(it != NULL){
printf("%s ", it -> word);
it = it -> next;
}
printf("\n");
}
void insertLast(struct node* tail, char* neww){
tail -> next = (struct node*)malloc(sizeof(struct node));
tail = tail -> next;
tail -> word = neww;
tail -> next = NULL;
}
struct node* words(char* s){
char* slowo = strtok(s, " ");
struct node* head;
struct node* tail;
if (sizeof(slowo) == 0)
return NULL ;
head = (struct node*)malloc(sizeof(struct node));
head -> word = slowo;
head -> next = NULL;
tail = head;
slowo = strtok(NULL, " ");
while (slowo != NULL){
insertLast(tail, slowo);
tail = tail -> next;
slowo = strtok(NULL, " ");
}
return head;
}
int main() {
printList(words("Some sentance la al olaalal"));
getch();
return (EXIT_SUCCESS);
}