我正在尝试编写一个函数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);
}
最佳答案
如果您不想 insertLast
在调用函数中设置 tail
,则必须通过引用传递指针(即作为指向指针的指针。) :
void insertLast(struct node** tail, char* neww)
在 insertLast
中使用正确的解引用才能使其正常工作。
关于c - 单链单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9160965/