2012-02-06 12 views
0

私は、パラメータとして渡されたテキストから単語の単一リンクリスト(スペースで区切られた文字のシーケンス)を生成する関数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); 
} 
+0

期待どおりに正確に機能しないものはありますか? 1つの問題を正確に記述してください。 – Dave

答えて

0

あなたwords()機能は、インプレース引数(s)を変更します。文字列リテラルでwords()を呼び出していて、文字列リテラルを変更することはできません。これに対処するには、strdup()またはmalloc()+strcpy()を使用してヒープ割り当てメモリにsを配置します。

1

あなたが呼び出し元の関数にtailを設定するinsertLastをwan't場合は、参照することにより、ポインタを渡す必要があり(ポインタへのポインタとしてすなわち。):

void insertLast(struct node** tail, char* neww) 

insertLastでの使用、適切な参照解除それが働くために。

関連する問題