0
试图用C编写一个程序,它创建一个队列并允许用户添加值。队列使用数组设置。不知何故,我的代码不工作,我想知道是否有人可以帮我排除故障。用C语言编写队列,我的代码出错的地方
#include <stdio.h>
#define CAP 10
//define a struct for our queue
typedef struct _que
{
int arr[CAP];
int front;
int size;
}
que;
void enqueue (que* ptr, int add);
int main(void)
{
int i;
que q1;
q1.front = 0;
q1.size = 0;
char yn = 'n';
//while loop for adding elements
do
{
printf("Enter the value you wish to add\n");
scanf("%d",&i);
enqueue(&q1, i);
printf("Would you like to add any more elements?\n");
scanf("%c",&yn);
}
while (yn == 'y' && q1.size <= CAP);
printf("The current element(s) in the queue are:");
//TODO: print out elements in the queue
for(int start = 0; start <= q1.size; start++)
{
printf("%d",q1.arr[start]);
}
printf("\n");
}
void enqueue(que* ptr, int add)
{
ptr->arr[((ptr->front)+(ptr->size))] = add;
ptr->size += 1;
}
程序正常执行到它打印的一部分“你想添加更多的元素”,那么它只是跳出do-while循环中,并打印在队列中的元素,这也因为它吐出垃圾值,如217836276,可能表示存在内存问题
解决了它,谢谢! –