鉴于希望从其内容中抽象出循环缓冲区的结构,并从以下代码段开始(由this http://en.wikipedia.org/wiki/Circular_buffer维基百科条目):
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 或介于两者之间的任何类型。我正在尝试做的事情可能吗?
正如您所发现的,您无法自动判断未知数据的大小。您将需要固定元素类型(void*
将是一个很好的通用选择),或者让用户传递每个元素的大小:
CircularBuffer *cbInit(uint16 size, int elementSize)
{
...
buffer->elementSize = elementSize;
buffer->elements = calloc(size, elementSize);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)