写一个C语言环形缓存的代码
时间: 2024-04-07 12:33:59 浏览: 120
基于C语言多个共享内存构成环形缓冲(操作系统实验)【100012384】
当然,请参考下面的示例代码,它展示了一个简单的环形缓冲区的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 10
typedef struct {
int* data;
int capacity;
int head;
int tail;
} CircularBuffer;
void initializeBuffer(CircularBuffer* buffer, int size) {
buffer->data = (int*)malloc(size * sizeof(int));
buffer->capacity = size;
buffer->head = 0;
buffer->tail = 0;
}
void enqueue(CircularBuffer* buffer, int value) {
buffer->data[buffer->tail] = value;
buffer->tail = (buffer->tail + 1) % buffer->capacity;
if (buffer->tail == buffer->head) {
buffer->head = (buffer->head + 1) % buffer->capacity;
}
}
int dequeue(CircularBuffer* buffer) {
int value = buffer->data[buffer->head];
buffer->head = (buffer->head + 1) % buffer->capacity;
return value;
}
int main() {
CircularBuffer buffer;
initializeBuffer(&buffer, BUFFER_SIZE);
// Enqueue some values
enqueue(&buffer, 10);
enqueue(&buffer, 20);
enqueue(&buffer, 30);
// Dequeue and print values
printf("%d\n", dequeue(&buffer));
printf("%d\n", dequeue(&buffer));
printf("%d\n", dequeue(&buffer));
free(buffer.data);
return 0;
}
```
这个示例代码演示了一个环形缓冲区的基本实现。它使用一个结构体 `CircularBuffer` 来保存数据和相关信息,使用 `initializeBuffer` 函数来初始化缓冲区,`enqueue` 函数向缓冲区中添加元素,`dequeue` 函数从缓冲区中取出元素。你可以根据自己的需求进行修改和扩展。
阅读全文