C 中的循环缓冲区

标签 c

我正试图在 C 中制作一种循环缓冲区。这是我现在拥有的。

#include <stdio.h>
#define ORDER 3
#define LENGTH 7

short input[LENGTH] = {1,2,3,4,5,6,7};
short buff[ORDER] = {0,0,0};
short pos = 0;

void filter(short input, short *buff, short *pos) {
    short p = *pos;       
    if (p==ORDER) {
        p=0;
    }
    p++; 
   *(buff+p) = input;
    printf("%d %d %d (%d)\n",*(buff+p),*(buff+p-1),*(buff+p-2),p);      
    *pos = p;    
}

void main() {
    short i;
    for (i=0;i<LENGTH;i++) {
        filter(input[i],buff,&pos);
    }
}

这个输出:

1 0 0 (1)
2 1 0 (2)
3 2 1 (3)
4 0 3 (1)
5 4 0 (2)
6 5 4 (3)
7 0 3 (1)

但是,我试图让它输出:

1 0 0 (1)
2 1 0 (2)
3 2 1 (3)
4 3 2 (1)
5 4 3 (2)
6 5 4 (3)
7 6 5 (1)

基本上,数字每次都会移动 1。我很确定我很接近,但我似乎无法做到这一点。

最佳答案

void filter(short input, short *buff, short *pos) {
    short p = *pos;       
    if (p==ORDER) {
        p=0;
    }
   *(buff+p) = input;
    printf("%hd %hd %hd (%hd)\n", buff[p],buff[p-1<0 ? p-1+ORDER : p-1],buff[p-2<0 ? p-2+ORDER : p-2], p+1);
    //printf("%hd %hd %hd (%hd)\n",buff[p],buff[(p-1+ORDER)%ORDER],buff[(p-2+ORDER)%ORDER], p+1);

    *pos = ++p;    
}

关于C 中的循环缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552224/

相关文章:

c - 动态访问结构体的成员变量

c - 在 STM32 上调用定时器回调时丢失指针地址

python - 指向python中指针的指针

缺少 Python.h header

c++ - 如何使用 PatchELF 或 chrpath 替换库共享对象

c - 在 linux 中使用 PF_PACKET 错误设置 IP_HDRINCL

c - 返回 C 中正因子计数的方法

c - mmap 和双指针

c - 如何定义链表节点 "recursively"?

C_icap 与 pthread 链接时出错