C语言中的循环缓冲区

C语言中的循环缓冲区,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;

我正在尝试用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 3 2 (1)
5 4 3 (2)
6 5 4 (3)
7 6 5 (1)

基本上,这些数字每次都会移动一个。我很确定我很接近,但我似乎无法实现这一点

你把事情弄得很复杂。尝试使用模运算符,而不是杂耍指针

short pos = 0;
short buff[ORDER];

void filter(short input) {
    buff[pos] = input;
    short second = (pos - 1) % ORDER;
    short third = (pos - 2) % ORDER;
    printf("%d %d %d (%d)\n", buff[pos], buff[second], buff[third], p);
    pos = (pos + 1) % ORDER;
}
void过滤器(短输入、短*缓冲、短*位置){
短p=*pos;
if(p==订单){
p=0;
}
*(buff+p)=输入;

printf(“%hd%hd%hd(%hd)\n)”,buff[p],buff[p-1这可以简化为:

void filter(short input, short *buff, short *pos) {
    buf[*pos] = input;
    printf("%d %d %d (%d)\n",buff[*pos],buff[(*pos+2)%ORDER],buff[(*pos+1)%ORDER],*pos);
    (++(*pos)) %= ORDER;
}

我只需要传递一个指向输入和要开始的索引的指针来进行过滤

void filter(short * input, short* pos){
    int i;
    for(i = *pos;i<ORDER;i--){
        printf("%d ",input[i] % ORDER);
    }
    printf("(%d) \n",*pos);
    *pos = (*pos + 1) % ORDER;
}

使用循环允许您在任意点更改order的值并打印任意范围的值。

您有几个明显的问题…1.*pos当
main()
调用
filter()
pos%order==0
时,您的程序会显示未定义的行为,因为
filter()
最终尝试计算
*(buff-1)
作为最后一个
printf()
参数。这是一个越界数组访问。看起来这些情况可能与错误行为有关。哦,对了。John是正确的。(我只是因为你的命名而感到困惑。。pos是一个指针)。这可能会修复它:printf(%d%d(%d)\n“,*(buff+(p%ORDER)),*(buff+(p+2%ORDER)),*(buff+(p+1%订单)),p);
void filter(short input, short *buff, short *pos) {
    buf[*pos] = input;
    printf("%d %d %d (%d)\n",buff[*pos],buff[(*pos+2)%ORDER],buff[(*pos+1)%ORDER],*pos);
    (++(*pos)) %= ORDER;
}
void filter(short * input, short* pos){
    int i;
    for(i = *pos;i<ORDER;i--){
        printf("%d ",input[i] % ORDER);
    }
    printf("(%d) \n",*pos);
    *pos = (*pos + 1) % ORDER;
}
filter(input,&pos);