Create a shared circular buffer

Given the desire to abstract the structure of the circular buffer from its contents and starting with the following code segments (courtesy of this wikipedia entry):

typedef struct { int value; } ElemType; typedef struct { int size; /* total number of elements */ int start; /* index of oldest element */ int count; /* index at which to write new element */ ElemType *elements; /* vector of elements */ } CircularBuffer; void cbInit(CircularBuffer *cb, int size) { cb->size = size; cb->start = 0; cb->count = 0; cb->elements = (ElemType *)calloc(cb->size, sizeof(ElemType)); } 

How to ignore the type of an element so that it is specified when defining an instance of a CircularBuffer? My attempt so far is this:

 CircularBuffer *cbInit(uint16 size, void *element) { CircularBuffer *buffer; buffer = malloc(sizeof(*buffer)); if (buffer != NULL) { buffer->size = size; buffer->start = 0; buffer->count = 0; buffer->elements = (void *)calloc(size, sizeof(???)); if (buffer->elements == NULL) { free(buffer); buffer = NULL; } } return buffer; } 

But I can’t understand how to determine the size of an unknown type, which can be int, struct or something in between. Is what I'm trying to do is even possible?

+4
c circular-buffer
source share
1 answer

As you found out, you cannot automatically indicate the size of an unknown piece of data. You will need either a fixed element type ( void* will be a good general choice) or the user will pass the size of each element:

 CircularBuffer *cbInit(uint16 size, int elementSize) { ... buffer->elementSize = elementSize; buffer->elements = calloc(size, elementSize); } 
+6
source share

All Articles