C言語でキューを表現したのですが、うまく動きません。

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
relrel

C言語でキューを表現したのですが、うまく動きません。

#1

投稿記事 by relrel » 8年前

こちらのプログラムなのですが、コンパイルは通りますし、特に問題はないとは思うのですが、enqを入力し新しい値を入力すると勝手にプログラムが終了します。endが入力されるまで続けたいのですが、わかる方いらっしゃいますか?

コード:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct cell {
    double num;
    struct cell *next;
};

int main(void) {
    struct cell *listhead = NULL;
    struct cell *listtail = NULL;
    struct cell *p;
    struct cell *q;
    char str[128];

    while (1) {
        printf("操作を選択してください (enq/deq/end) ==> ");
        scanf("%s", str);

        if (strcmp(str, "enq") == 0) {
            p = (struct cell *)malloc(sizeof(struct cell));

            printf("追加する値を入力してください ==> ");
            scanf("%lf", &(p->num));

            if (listhead == NULL) {
                listhead = p;
                listtail = p;

            } else {
                listtail->next = p;
                p = listtail;

            }

            p = listhead;
            while (p != NULL) {
                printf("->%f", p->num);
                p = p->next;

            }

        } else if (strcmp(str, "deq") == 0) {
            if (listhead == NULL) {
                printf("キューにデータがありません。\nプログラムを終了します。\n");
                break;

            } else {
                p = listhead;
                listhead = listhead->next;
                printf("&fを削除しました。\n", p->num);
                free(p);

                p = listhead;
                while (p != NULL) {
                    printf("->%f", p->num);
                    p = p->next;
                
                }

            }
            
        } else if (strcmp(str, "end") == 0) {
            printf("プログラムを終了します。\n");
            
            p = listhead;
            while (p != NULL) {
                q = p->next;
                free(p);
                p = q;
            }

            break;
            
        }

    }

    return 0;
}


アバター
みけCAT
記事: 6734
登録日時: 14年前
住所: 千葉県
連絡を取る:

Re: C言語でキューを表現したのですが、うまく動きません。

#2

投稿記事 by みけCAT » 8年前

40行目でmallocで確保されて初期化されていない不定の値p->nextがpに代入され、その値が38行目のp != NULLで計算に使用され、未定義動作になります。
使用する前(例えば22行目の直後)にp->nextを(例えばNULLに)初期化しなければいけません。
また、mallocが万が一失敗する場合に備え、戻り値がNULLでないかをチェックするべきです。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

かずま

Re: C言語でキューを表現したのですが、うまく動きません。

#3

投稿記事 by かずま » 8年前

27~35行目を次のように修正してみてください。

コード:

            p->next = NULL;
            if (listhead == NULL)
                listhead = p;
            else
                listtail->next = p;
            listtail = p;
52行目の printf の書式の &f は、%f または %g にしましょう。

また、次のようなリスト表示関数を用意し、

コード:

void print(const struct cell *p)
{
    for (; p; p = p->next) printf("->%g", p->num);
    printf("\n");
}
37~42、55~60行目のリスト表示を、print(listhead); にするのはいかがですか?

返信

“C言語何でも質問掲示板” へ戻る