Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I code a simple integer circular buffer in C/C++?

I see a lot of templates and complicated data structures for implementing a circular buffer.

How do I code a simple integer circular buffer for 5 numbers?

I'm thinking in C is the most straightforward?

Thanks.

like image 448
T.T.T. Avatar asked Sep 01 '10 20:09

T.T.T.


People also ask

How would you implement a simple circular buffer in C?

First, we need to store the size of the circular buffer that we're implementing. A good way to store this information is in a constant. Next, we'll need a variable to store the buffer length. The buffer length is the current number of filled elements (elements we've written to).

What is circular buffer in C?

Circular buffers (also known as ring buffers) are fixed-size buffers that work as if the memory is contiguous & circular in nature. As memory is generated and consumed, data does not need to be reshuffled – rather, the head/tail pointers are adjusted. When data is added, the head pointer advances.

Where are circular buffers used?

A circular buffer is a utility used to transfer successive data values from a producer thread to a consumer thread, who retrieves the data in FIFO (first in first out) order. This kind of data structure will be used when pipelining threads, a subject discussed in detail in Chapter 15.

What is the difference between circular buffer and circular queue?

A Circular Queue is an extension of the Queue data structure such that the last element of the queue links to the first element. It is known as Ring Buffer, Circular Buffer or Cyclic Buffer. In Linear Queue Data Structure, we have two pointers Front and Rear.


2 Answers

Have an array, buffer, of 5 integers. Have an index ind to the next element. When you add, do

buffer[ind] = value;
ind = (ind + 1) % 5;
like image 69
Matthew Flaschen Avatar answered Sep 20 '22 17:09

Matthew Flaschen


Take an array, arr, an index idx, and a counter, num.

To insert foo, say arr[idx++] = foo; idx %= buffer_len; num++;.

To read out an item into foo, say foo = arr[(idx-num)%buffer_len]; num--;.

Add boundary checks.

like image 37
Borealid Avatar answered Sep 21 '22 17:09

Borealid