Search code examples
carraysqueueavr

Array of Chars as Queue in C


I'm coding a piece of code for AVR. I want to build a queue that can push and pop, and this queue is an array of chars (string). So when I push 'a':
['b', 'c', 'd', 'e', 'f']
becomes:
['a','b', 'c', 'd', 'e', 'f']
and when I pop, f comes out. I've written this code, but it only pushes 1 char to the queue, as if it removes the whole queue. Here's my code for the queue:

char queue[50] = "";
char* queue_tail = &queue[0];
char* queue_head = &queue[0];

void queue_push(char l_item)
{
    if(queue_head != &queue[strlen(queue) - 1]) //if queue is not full, do the job
    {
        //Push all elements one step further
        char* traveler = queue_head;
        for(; traveler != queue_tail; --traveler)
        {
            *(traveler+1) = *traveler;
            *traveler = '';
        }
        ++queue_head;
        *queue_tail = l_item;
    }
}

char queue_pop()
{
    char temp = *queue_head;
    *queue_head = '';
    --queue_head;
    return temp;
}

This is my main function:

#include <mega32.h>
#include <alcd.h>
#include <delay.h>
#include <string.h>

void main(void)
{

const char text[] = "Hello world!";
int col_counter = 0;
char* p_head = '';

lcd_init(32);
p_head = &text[12];

while(1)
{
    lcd_clear();

    if(col_counter + strlen(text) > 32)
    {
        queue_push(*p_head);
        --p_head;
    }

    lcd_gotoxy(col_counter, 0);
    lcd_puts(text);
    lcd_gotoxy(0,0);
    lcd_puts(queue);
    delay_ms(200);
    ++col_counter;

}
}

Any help would be appreciated. Thanks in advance.


Solution

  • I changed the meaning of queue_head from the last element to one past the last element in the queue, and adjusted the code.

    Here is a corrected code (main() in this code is a test code for usual PC):

    #include <stdio.h>
    
    char queue[50] = "";
    char* queue_tail = &queue[0];
    char* queue_head = &queue[0];
    
    void queue_push(char l_item)
    {
        if(queue_head != queue + sizeof(queue)/sizeof(*queue)) //if queue is not full, do the job
        {
            //Push all elements one step further
            char* traveler = queue_head;
            for(; traveler != queue_tail; --traveler)
            {
                *traveler = *(traveler - 1);
            }
            ++queue_head;
            *queue_tail = l_item;
        }
    }
    
    char queue_pop(void)
    {
        char temp;
        if (queue_head == queue_tail) return '\0'; // the queue is empty
        --queue_head;
        temp = *queue_head;
        *queue_head = '\0';
        return temp;
    }
    
    int main(void) {
        queue_push(100);
        queue_push(110);
        printf("%d\n",queue_pop());
        printf("%d\n",queue_pop());
        return 0;
    }