C语言写一个ring buff
时间: 2024-05-30 18:13:06 浏览: 76
c语言实现循环buffer
er(环形缓冲区)的代码怎么写?
以下是一个简单的 C 语言环形缓冲区的示例代码:
typedef struct {
int head;
int tail;
int size;
int *data;
} RingBuffer;
void RingBuffer_Init(RingBuffer *buffer, int size) {
buffer->head = 0;
buffer->tail = 0;
buffer->size = size;
buffer->data = (int*) malloc(sizeof(int) * size);
}
void RingBuffer_Enqueue(RingBuffer *buffer, int value) {
int next_tail = (buffer->tail + 1) % buffer->size;
if (next_tail != buffer->head) {
buffer->data[buffer->tail] = value;
buffer->tail = next_tail;
}
}
int RingBuffer_Dequeue(RingBuffer *buffer) {
if (buffer->tail != buffer->head) {
int value = buffer->data[buffer->head];
buffer->head = (buffer->head + 1) % buffer->size;
return value;
} else {
return -1;
}
}
void RingBuffer_Free(RingBuffer *buffer) {
free(buffer->data);
}
在上述代码中,RingBuffer_Init 函数用于初始化环形缓冲区,RingBuffer_Enqueue 函数用于将元素放入缓冲区中,RingBuffer_Dequeue 函数用于从缓冲区中取出元素。RingBuffer_Free 函数则用于释放环形缓冲区所占用的内存空间。
阅读全文