Hi need a little help. I want to implement a 19 element circular array. Not a queue, and not a list; just a regular array. How can I make it circular? All
I can think of is: lastFieldIndex+1=firstFieldIndex.
The trick with the circular buffer (being implemented as an array), is keeping track of where in the buffer you are. I don't particularly like the modulus method due to the fact that it is possible that you overflow your index.
#define ARR_LEN 19
int arr[ARR_LEN];
int idx = 0;
void insert(int value);
int main(void)
{
for (int i = 0; i < ARR_LEN + (ARR_LEN / 2); i++)
{
insert(i);
}
return 0;
}
void insert(int value)
{
arr[idx] = value;
if (idx == ARR_LEN - 1)
idx = 0;
else
idx++;
}
Printing the array is a little tricky. You need to be able to know whether you have inserted beyond the length of the array (if idx = 12, does this mean that 0-11 are should be printed, or 12-MaxLength and 0 - 11 need printing?). I guess you could add a global boolean to take care of that for you.