C语言实现环形缓冲区
时间: 2023-08-20 11:10:08 浏览: 67
可以使用数组来实现环形缓冲区。下面是一个简单的示例代码:
```c
#define BUFFER_SIZE 10
typedef struct {
int buffer[BUFFER_SIZE];
int head; // 缓冲区头部索引
int tail; // 缓冲区尾部索引
} CircularBuffer;
// 初始化环形缓冲区
void initCircularBuffer(CircularBuffer* cb) {
cb->head = 0;
cb->tail = 0;
}
// 向环形缓冲区中写入数据
void writeCircularBuffer(CircularBuffer* cb, int data) {
cb->buffer[cb->tail] = data;
cb->tail = (cb->tail + 1) % BUFFER_SIZE;
}
// 从环形缓冲区中读取数据
int readCircularBuffer(CircularBuffer* cb) {
int data = cb->buffer[cb->head];
cb->head = (cb->head + 1) % BUFFER_SIZE;
return data;
}
```
使用示例:
```c
int main() {
CircularBuffer cb;
initCircularBuffer(&cb);
writeCircularBuffer(&cb, 10);
writeCircularBuffer(&cb, 20);
writeCircularBuffer(&cb, 30);
int data1 = readCircularBuffer(&cb);
int data2 = readCircularBuffer(&cb);
printf("%d\n", data1); // 输出: 10
printf("%d\n", data2); // 输出: 20
return 0;
}
```
这个示例中,我们使用数组 `buffer` 来存储数据,使用 `head` 和 `tail` 分别表示缓冲区的头部和尾部索引。在写入数据时,将数据存储在 `tail` 所指向的位置,并将 `tail` 的索引递增一位。在读取数据时,从 `head` 所指向的位置读取数据,并将 `head` 的索引递增一位。当 `tail` 或 `head` 达到缓冲区的末尾时,我们使用取余运算将其重新定位到缓冲区的开头,实现了循环利用缓冲区的效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)