Skip to content

28 环形队列 · 回绕、判空与判满 ​

预留一个空槽位,next == read 表示满,read == write 表示空。本例在同一执行上下文中运行。

源码 ​

main.c ​

下载 main.c

c
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

enum { CAP = 4 };
typedef struct {
    uint8_t data[CAP];
    unsigned read, write;
} Ring;

static bool push(Ring *r, uint8_t value)
{
    unsigned next = (r->write + 1u) % CAP;
    if (next == r->read) return false;
    r->data[r->write] = value;
    r->write = next;
    return true;
}

static bool pop(Ring *r, uint8_t *value)
{
    if (r->read == r->write) return false;
    *value = r->data[r->read];
    r->read = (r->read + 1u) % CAP;
    return true;
}

int main(void)
{
    Ring r = {0};
    uint8_t value;
    push(&r, 10);
    push(&r, 20);
    push(&r, 30);
    if (!push(&r, 40)) puts("full");
    pop(&r, &value);
    push(&r, 40);
    while (pop(&r, &value)) {
        printf("%u%c", (unsigned)value, r.read == r.write ? '\n' : ' ');
    }
    return 0;
}

主机运行 ​

在仓库根目录执行。Windows 可以将输出名写成 reading-28.exe,再从终端运行。

sh
gcc -std=c11 -Wall -Wextra -pedantic examples/c-reading/28/main.c -o reading-28
./reading-28

先沿 main() 预测打印结果,再展开核对。

主机输出与手推
text
full
20 30 40

长度 4 可存 3 个字节。第一次写 40 遇满,读走 10 后重试成功。

练习 ​

实现 count,分别手推 write 大于和小于 read 两种情况。

关联模板 ​

环形缓冲区的完整读写模板

验证记录 ​

主机版使用 GCC 编译运行,输出与跟读材料逐项核对。

上一课 27 · 跟读目录 · 下一课 29