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; int start; int count; ElemType *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?
c circular-buffer
Zack
source share