我正试图在 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/