Home > Blockchain >  Circular buffer with void pointer parameter
Circular buffer with void pointer parameter

Time:09-27

What is the right way to write this code? I want to make a circular buffer that will receive as a parameter a pointer to some type of data. This way I wrote not working. I have problem with circular_buf_put function. It says invalid use of void expression. error: invalid use of void expression cb->data[cb->head]=data; What is right way to use it here?

typedef struct circular_buf{
    void *data;
    size_t tail;
    size_t head;
    size_t capacity;
    size_t objectSize; 
    size_t size; 
} circular_buf;

int circular_buf_init(struct circular_buf *cb, void *data, size_t objectSize, size_t capacity)
  {
  cb->data=data;
  cb->objectSize=objectSize;
  cb->capacity=capacity;
  cb->tail=0;
  cb->head=0;
  cb->size=0;
   }

void circular_buf_put(circular_buf *cbuf, void  *data)
{
    cbuf->data[cbuf->head] = data;
    cbuf->head  ;
    cbuf->size  ;

}

CodePudding user response:

it say invalid use of void expression.

Because of this line:

cbuf->data[cbuf->head] = data;

You are dereferencing a void pointer, which is illegal in C. You need to cast it to another type before you can dereference it.

CodePudding user response:

I would implement it this way. You do not need so much information in the structure. You only need to know the tail, head, size in elements and the element size.

typedef struct
{
    size_t tail;
    size_t head;
    size_t size; 
    size_t obj_size;
    unsigned char data[];
} circular_buf;

circular_buf *create(size_t size, size_t obj_size)
{
    circular_buf *cb = malloc(sizeof(*cb)   size * obj_size);
    if(cb)
    {
        cb -> tail = 0;
        cb -> head = 0;
        cb -> size = size;
        cb -> obj_size = obj_size;
    }
    return cb;
}

size_t inc(size_t val, circular_buf *cb)
{
    if(val == cb -> size - 1) val = 0;
    else val  ;

    return val;
}

int circular_buf_put(circular_buf *cb, const void *data)
{
    size_t new_tail = inc(cb -> tail, cb);
    if (new_tail == cb -> head) return -1; // buffer full
    memcpy(&cb->data[cb -> tail * cb -> size], data, cb -> obj_size);
    cb -> tail = new_tail;
    return 0;
}

  •  Tags:  
  • c
  • Related