[Solved] trying to create a circular buffer in C++ using struct


supposing head is the index where you place a new value, when you push a value temp.head++;must be replaced by temp.head = (temp.head + 1) % BUFFER_LENGTH; to manage the length of the buffer. You also have to move the tail when the buffer is full.

I do not understand why you push 1 value then write 5 values

You say you are in C++, so why do you write in C ? why you do not have a constructor and push/pop/top operation on ringbuffer ?

{edit add}

As you requested a very simple way to do in c++

#include <iostream>
using namespace std;

#define LENGTH_BUFFER 4

// in c++ we use a struct when all members are public (by default all is public in a struct),
// but this is dangerous because all can be modified from outside without any protection,
// so I prefer to use a class with public/private parts

class RingBuffer {
  public:
    // The constructor, it replaces RingBuffer_Init,
    // The big advantage is you cannot miss to call the constructor
    RingBuffer();

    // it is not needed to have a destructor, the implicit destructor is ok

    // because it is an operation you do not have to give the ringbuffer in parameter
    void push(int data);

    // I had the print operation, it print following the order of insertion
    // to print doesn't change the instance, so I can say the operaiotn is 'const'
    void print() const;

  private:
    int buffer[LENGTH_BUFFER];
    int head; // index of the future value
    int tail; // index of the older inserted value, except if empty / head == index
};

// The buffer is initialized empty, head == tail
// I can initialize the indexes by any other valid
// value, this is not relevant
RingBuffer::RingBuffer() : head(0), tail(0) {
}

// push a new value, 
void RingBuffer::push(int data)
{
  buffer[head] = data;
  head = (head + 1) % LENGTH_BUFFER;

  if (head == tail)
    tail = (tail + 1) % LENGTH_BUFFER;
}

// print the content and indexes
void RingBuffer::print() const {
  for (int p = tail; p != head; p = (p + 1)  % LENGTH_BUFFER)
    cout << buffer[p] << ' ';
  cout << " (head=" << head << ", tail = " << tail << ')'  << endl;
}

int main()
{
  RingBuffer test;

  test.print();

  test.push(1);
  test.print();

  test.push(2);
  test.print();

  test.push(3);
  test.print();

  test.push(4);
  test.print();

  test.push(5);
  test.push(6);
  test.print();

  return 0;
}

I reduced the size of the buffer to rotate with few values.

The execution produces :

 (head=0, tail = 0)
1  (head=1, tail = 0)
1 2  (head=2, tail = 0)
1 2 3  (head=3, tail = 0)
2 3 4  (head=0, tail = 1)
4 5 6  (head=2, tail = 3)

As you can see in that implementation one entry is lost, it has the size 4 but manages only 3 values. I let you can change that, add top(), back(), pop() etc

9

solved trying to create a circular buffer in C++ using struct