6

割り当て用の入力テキストファイルから単一リンクリストを作成しようとしています。一度に少しずつ実行しようとしているので、コードが完全ではないことがわかります。ヘッドポインタを作成してその値を出力しようとしましたが、それを機能させることすらできませんが、理由はわかりません。構造体、リストの作成、リストの印刷機能を含めました。その部分が機能するので、開いているファイルを含めませんでした。

typedef struct List
{
   struct List *next;   /* pointer to the next list node */
   char *str;           /* pointer to the string represented */
   int count;           /* # of occurrences of this string */
} LIST;

LIST *CreateList(FILE *fp) 
{
    char input[LINE_LEN];
    LIST *root;             /* contains root of list             */
    size_t strSize;         
    LIST *newList;          /* used to allocate new list members */

    while (fscanf(fp, BUFFMT"s", input) != EOF) {

        strSize = strlen(input) + 1;

        /* create root node if no current root node */
        if (root == NULL) {
            if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) {
                printf("Out of memory...");
                exit(EXIT_FAILURE);
            } 
            if ((char *)malloc(sizeof(strSize)) == NULL) {
                printf("Not enough memory for %s", input);
                exit(EXIT_FAILURE);
            }
                memcpy(newList->str, input, strSize);   /*copy string    */
                newList->count = START_COUNT;
                newList->next = NULL;
                root = newList;
        }
    }
        return root;
}

/* Prints sinly linked list and returns head pointer */
LIST *PrintList(const LIST *head) 
{
    int count;

    for (count = 1; head != NULL; head = head->next, head++) {
        printf("%s    %d", head->str, head->count);
    }                       
    return head;     /* does this actually return the start of head ptr, b/c I want to 
                            return the start of the head ptr. */
}
4

3 に答える 3

2

root値が未定義であるため、初期化されません。の2行目CreateList

LIST *root = NULL;

また、アイテムの詳細については明らかに割り当てがありますが、a)コードが割り当てをキャプチャしてどこにでも保存できず、b)割り当てのサイズはstrSize、変数自体の長さではなく、である必要があります。これを修正する方法はいくつかありますが、最も簡単な方法は次のとおりです。

newList->str = (char *)malloc(strSize);
if (newList->str == NULL)
于 2010-02-22T07:16:50.290 に答える
1

head = head->nextforループの後で頭をインクリメントするべきではありません。ループはheadがNULLになるまで停止しないため、PrintListは毎回NULLを返します。とにかく関数に渡したばかりのリストの先頭を返す必要があるのはなぜですか?

編集:

LIST *current = head;
while (current != NULL) {
    printf("%s    %d", current->str, current->count);
    current = current->next;
}
于 2010-02-22T07:18:54.630 に答える
1

2 番目の malloc はメモリを割り当てますが、その戻り値は何にも割り当てられないため、割り当てられたメモリは失われます。

newList は割り当てられていますが初期化されていないため、memcpy を使用してメモリを newList->str にコピーすると、newList->str が何も指していないため失敗します。おそらく、2 番目の malloc の結果を newList->str に代入したかったのですが、それを忘れていました。

于 2010-02-22T07:40:23.783 に答える