circular buffer 的 sample

能不能幫我示範一個FIFO的circular buffer的sample, 並符合下列條件

Practice: Implement a queue by circular buffer

Hint 1: use a macro to define the max queue length

Hint 2: declare a structure to record

the array

the start index

the end index

Hint 3: write a function to initialize the queue

Hint 4: write two functions to test emptiness/fullness of the queue

Hint 5: write a function to enqueue

Hint 6: write a function to dequeue

Hint 7: use assertions to detect invalid enqueue/dequeue conditions

Hint 8: write a function to print the available data items in the queue

Hint 9: write a test program to simulate the buffering of a sequence of data

1 Answer

  • Wu
    Lv 5
    1 decade ago
    Favorite Answer

    #include <assert.h>

    #define MAX_QUEUE 10

    typedef struct

    { int data[MAX_QUEUE];

    int start;

    int end;

    int ndata;

    } BUFFER;

    void initBuffer(BUFFER *buf)


    buf->start = buf->end = buf->ndata = 0;


    int isEmpty(BUFFER *buf)


    return (buf && !buf->ndata);


    int isFull(BUFFER *buf)


    return (buf && buf->ndata == MAX_QUEUE);


    void enQueue(BUFFER *buf, int num)

    { assert(buf && !isFull(buf));

    buf->data[buf->end++] = num;

    buf->end %= MAX_QUEUE;



    int deQueue(BUFFER *buf)

    { int data;

    assert(buf && !isEmpty(buf));

    data = buf->data[buf->start++];

    buf->start %= MAX_QUEUE;


    return data;


    void printData(BUFFER *buf)

    { int i,n;

    if (buf && !isEmpty(buf))

    for (n=0,i=buf->start;n<buf->ndata; ++n, ++i, i%=MAX_QUEUE) printf("%d\n",buf->data[i]);


    void main()

    { BUFFER buf;

    int i;


    for (i=1; i<=MAX_QUEUE; ++i) enQueue(&buf, i);

    printf("queued data:\n");


    printf("dequeuing %d\n",deQueue(&buf));

    printf("dequeuing %d\n",deQueue(&buf));



    printf("updated data:\n");



Still have questions? Get your answers by asking now.