Content deleted Content added
Filled in 0 bare reference(s) with reFill 2 |
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>
enum { N = 10 }; // N elements of the circular buffer
int buffer [N]; // Note that N-1 is the actual capacity, see put function
void put(int item)▼
int writeIndx = 0;
int readIndx = 0;
{
if ((writeIndx + 1) % N == readIndx)
buf[end++] = item;▼
{
// buffer is full, avoid overflow
return 0;
}
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
{
// test circular buffer
int value
while (put
while (get (& value))
printf ("read %d\n", value);
return 0;
}
</syntaxhighlight>
|