【问题标题】:Programming a queue in C, where did my code go wrong用C编程队列,我的代码哪里出错了
【发布时间】:2016-07-24 15:56:14
【问题描述】:

试图用 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 这样的垃圾值,可能表示内存问题

【问题讨论】:

    标签: c


    【解决方案1】:

    您的条件start &lt;= q1.size 是错误的,它包含off-by-one error。应该是start &lt; q1.size

    为避免将空格字符读入yn,应在%c 之前添加一个空格,如scanf(" %c",&amp;yn); 以使scanf() 跳过空格字符。

    还要注意条件q1.size &lt;= CAP对于防止缓冲区溢出也是错误的,它应该是q1.size &lt; CAP

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-13
      • 2016-08-02
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多