Circular buffer: Difference between revisions

Content deleted Content added
Filled in 0 bare reference(s) with reFill 2
Elxala (talk | contribs)
The C implementation was unacceptable, it would overwrite data if buffer is full and allow reading data even if buffer is empty (read garbage).
Line 65:
Another solution is to have another integer count that is incremented at a write operation and decremented at a read operation. Then checking for emptiness means testing count equals 0 and checking for fullness means testing count equals Length.<ref>{{cite web |title=ArrayQueue: An Array-Based Queue |url=http://opendatastructures.org/ods-python/2_3_ArrayQueue_Array_Based_.html |website=Open Data Structures (in pseudocode) |first=Pat |last=Morin|author-link= Pat Morin |access-date=7 November 2015 |archive-url=https://web.archive.org/web/20150831023453/http://opendatastructures.org/ods-python/2_3_ArrayQueue_Array_Based_.html |archive-date=31 August 2015 |url-status=live }}</ref>
 
The following source code is a C implementation together with a minimal test. Function put() puts an item in the buffer, function get() gets an item from the buffer. Both functions takes care about the capacity of the buffer :
 
<syntaxhighlight lang="c">
#include <stdio.h>
#define BUFLEN 3
 
enum { N = 10 }; // N elements of the circular buffer
int buf[BUFLEN]; /* array to be treated as circular buffer of BUFLEN integers */
int end = 0; /* write index */
int start = 0; /* read index */
 
int buffer [N]; // Note that N-1 is the actual capacity, see put function
void put(int item)
int writeIndx = 0;
int readIndx = 0;
 
voidint put (int item)
{
if ((writeIndx + 1) % N == readIndx)
buf[end++] = item;
{
end %= BUFLEN;
// buffer is full, avoid overflow
return 0;
}
bufbuffer[end++writeIndx] = item;
writeIndx = (writeIndx + 1) % N;
return 1;
}
 
int get (int * value)
{
if (readIndx == writeIndx)
{
// buffer is empty
return 0;
}
 
*value = buffer[readIndx];
readIndx = (readIndx + 1) % N;
return 1;
}
 
int getmain ()
{
// test circular buffer
int item = buf[start++];
int value start %= BUFLEN1001;
while (put return(value item++));
while (get (& value))
printf ("read %d\n", value);
return 0;
}
</syntaxhighlight>