【发布时间】:2016-02-04 10:50:35
【问题描述】:
我尝试在 C 中实现环形缓冲区/循环队列。
它应该通过 argv 获取所有参数,将它们一个一个地推入队列,然后以相同的方式将它们从队列中弹出,并在输出时打印出来。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>
struct buffer
{
int32_t front, rear, capacity, *array;
};
__attribute__ ((noreturn)) void prog_error(const char* str)
{
perror(str);
exit(1);
}
struct buffer *init_queue(int32_t size)
{
struct buffer *queue = malloc(sizeof(struct buffer));
if (!queue)
return NULL;
queue->capacity = size;
queue->front = -1;
queue->rear = -1;
queue->array = malloc(queue->capacity * sizeof(int32_t));
if (!queue->array)
return NULL;
return queue;
}
void enqueue(struct buffer *queue, int32_t x)
{
if (((queue->rear + 1) % queue->capacity == queue->rear))
prog_error("Queue overflow");
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = x;
if (queue->front == -1)
queue->front = queue->rear;
}
int32_t dequeue(struct buffer *queue)
{
int32_t data = 0;
if (queue->front == -1)
prog_error("Queue underflow");
data = queue->array[queue->front];
if (queue->front == queue->rear)
queue->front = queue->rear = -1;
queue->front = (queue->front + 1) % queue->capacity;
return data;
}
int main(int argc, char **argv)
{
if (argc < 2)
prog_error("Too few arguments");
int32_t size = (int32_t) argc - 1;
struct buffer *queue;
if (!(queue = init_queue(size)))
prog_error("Allocation error");
for (int32_t i = 1; i < size; ++i)
enqueue(queue, (int32_t) atoi(argv[i]));
for (int32_t i = 0; i < size; ++i)
printf("%" PRId32 "\n", dequeue(queue));
free(queue);
}
但最后一个值总是用 1 代替。
而且,如果我给它正好 1 个值,那么它就会下溢(或者这是环形缓冲区的正常行为?)。 我该如何解决这个问题?
【问题讨论】:
-
您的输入、实际输出和预期输出是什么?
-
输入:./ringbuffer 0 1 2 3 4 期望输出:0 1 2 3 4 实际输出:0 1 2 3 1
标签: c linux data-structures queue circular-buffer