circular array

Sep 14, 2012 at 11:48pm
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.
Sep 14, 2012 at 11:55pm
use modulus operator.

example:

1
2
3
4
5
6
const int ARR_LEN = 10;

int arr[ARR_LEN] = {0,1,2,3,4,5,6,7,8,9};

for (int i = 0; i < ARR_LEN * 2; ++i)
    cout << arr[i % ARR_LEN] << " ";  //0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9  
Sep 15, 2012 at 12:49am
tntxnt's method works well.

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.

I would just keep track of when to subract:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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.

I made this for char**, maybe helps?
http://www.cplusplus.com/forum/beginner/74456/
Last edited on Sep 15, 2012 at 12:56am
Topic archived. No new replies allowed.