[英]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.