簡體   English   中英

程序產生錯誤的輸出

[英]Program produce Wrong output

我已經編寫了有關隊列和動態內存分配的程序。 這是我的程序需要做的-將值插入到隊列中並將其從隊列中刪除; 這么簡單。 但是我的問題是,它只顯示值分配給變量的變量的名稱,而程序沒有響應。

這是我的程序:

#include <stdio.h>
#define MAX 180

struct cakes{
        int spongecake;
        int meringue;
        int chocalate;
        int red_velvet;
        struct newcake *next;
};

struct Queue{
        int front;
        int rear;
        int count;
        int cake[10];
};

void init(struct Queue *);
int isFull(struct Queue *);
void insert(struct Queue *,int);
int isEmpty(struct Queue *);
int removes(struct Queue *);

void cake_order(struct cakes *);
void order_out(struct cakes *);

main()
{
        struct cakes *head;

        head=(struct cakes *)malloc(sizeof(struct cakes ));
        cake_order(&head); //this is a seperate function and it works perfectly
        head->next=(struct cakes *)malloc(sizeof(struct cakes));
        order_out(&head->next);
}
void init(struct Queue *q)
{
        q->front=0;
        q->rear=10-1;
        q->count=0;
}

int isFull(struct Queue *q)
{
        if(q->count==10)
        {
                return 1;
        }
        else 
        {
                return 0;
        }
}

void insert(struct Queue *q,int x)
{
        if(!isFull(q))
        {
                q->rear=(q->rear+1)%10;
                q->cake[q->rear]=x;
                q->count++;
        }

}

int isEmpty(struct Queue *q)
{
        if(q->count==0)
        {
                return 1;
        }
        else
        {
                return 0;
        }
}

int removes(struct Queue *q)
{
        int caked=NULL;

        if(!isEmpty(q))
        {
                caked=q->cake[q->front];
                q->front=(q->front+1)%10;
                q->count--;
                return caked;
        }
}

void order_out(struct cakes *order)
{
        struct Queue s;
        int i;  

        order->spongecake=20;
        order->meringue=75;
        order->chocalate=40;
        order->red_velvet=30;

        init(&s);

        for(i=0;i<10;i++)
        {
                insert(&s,order->chocalate);
                insert(&s,order->spongecake);
                insert(&s,order->meringue);
                insert(&s,order->red_velvet);
    }

        while(!isEmpty(&s)) 
        {   
                printf("%d",removes(&s));
        }
}

這里似乎是什么問題? 我是C語言的新手,所以用這種語言調試時有點慢。

感謝您的時間。

這是輸出:

在此處輸入圖片說明

這里的問題很多,首先它會更好,如果main被宣布為正確的int main()然后返回在最后例如值return 0; 喜歡:

int main()
{
    .... // code

    return 0; // normally 0 is returned if execution has been successful
}

由於我無法編譯該代碼,因此似乎還有其他問題,例如, order_out()在while循環之后order_out()右括號。

如果您提供了cake_order()函數, cake_order()也將很好。

它還缺少stdlib.h之類的include,在第45行( head=(struct cakes *)malloc(sizeof(struct cakes )); )我注意到您強制轉換了malloc的結果, 這不是必需的

而且,如果我可能還要補充一點,請不要忘記free()malloc()分配的malloc() 我在您的代碼中沒有看到任何free()語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM