我試圖編寫一個函數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);
}
什麼不正如你所料?嘗試準確地描述您遇到的單個問題。 – Dave 2012-02-06 13:48:06