4

鉴于希望从其内容中抽象出循环缓冲区的结构,并从以下代码段开始(由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 或介于两者之间的任何类型。我正在尝试做的事情甚至可能吗?

4

1 回答 1

7

正如您所发现的,您无法自动判断未知数据的大小。您将需要一个固定的元素类型(void*将是一个很好的通用选择),或者让用户传递每个元素的大小:

CircularBuffer *cbInit(uint16 size, int elementSize)
{
    ...
    buffer->elementSize = elementSize;
    buffer->elements    = calloc(size, elementSize);  
}
于 2012-11-29T02:53:13.330 回答