I am trying to implement the simplest circular buffer in Arduino. I think I am able to implement it because my push and pop functions do not return any errors. However, when I want to print the data in the buffer using Serial.print(), the code goes into an infinite loop. Here is my code:
#include <stdio.h>
typedef struct circular_buffer
{
int buffer_arr[5];
int head;
int tail;
} circular_buffer;
void setup()
{
Serial.begin(9600);
Serial.println("Circular buffer started");
}
void loop()
{
circular_buffer *cb;
cb_init(cb);
if(Serial.available()){
char instruction = Serial.read();
Serial.println(instruction);
if(instruction == 'a'){
if(Serial.available()){
char instruction = Serial.read();
Serial.println("here");
}
char key = Serial.read();
cb_push_front(cb, key);
Serial.print(String(key));
Serial.println(" is entered");
}
else if(instruction == 'd'){
cb_pop_back(cb);
Serial.println("last item removed");
}
// for(int i=0; i<5; i++){
// Serial.print(cb->buffer_arr[i]);
//
// }
Serial.println("-");
}
}
void cb_init(circular_buffer *cb)
{
// cb->buffer_arr = {0,0,0,0,0};
for(int i=0; i<5; i++){
cb->buffer_arr[i] = 'c';
// Serial.print(sizeof(*cb));
}
// Serial.print(cb->buffer_arr[0]);
cb->head = 0;
cb->tail = 0;
}
void cb_push_front(circular_buffer *cb, char item)
{
cb->head++;
cb->buffer_arr[cb->head] = item;
}
void cb_pop_back(circular_buffer *cb)
{
cb->tail++;
cb->buffer_arr[cb->tail] = 0;
}
The for loop which I commented out is the problematic one - or at least what I believe. My problem can be very much related to my poor C-language skills. I thought that cb->buffer_arr = {0,0,0,0,0}; code piece in the initialization function should have worked (thinking very much Python-ic way) but it didn't.
So, if anyone can see the issue and help me fixing it, I'd be very much appreciated.
Thanks in advance.