鉴于希望从其内容中抽象出循环缓冲区的结构,并从以下代码段开始(由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));
}
如何抽象元素类型以便在定义 CircularBuffer 实例时指定它?到目前为止,我的尝试如下:
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;
}
但我不知道如何确定未知类型的大小,它可能是 int、struct 或介于两者之间的任何类型。我正在尝试做的事情甚至可能吗?