我已經看到了下面的實現循環緩衝區:問題有關C實現循環緩衝區的
http://en.wikipedia.org/wiki/Circular_buffer
/**< Buffer Size */
#define BUFFER_SIZE 10
#define NUM_OF_ELEMS (BUFFER_SIZE-1)
/**< Circular Buffer Types */
typedef unsigned char INT8U;
typedef INT8U KeyType;
typedef struct
{
INT8U writePointer; /**< write pointer */
INT8U readPointer; /**< read pointer */
INT8U size; /**< size of circular buffer */
KeyType keys[0]; /**< Element of circular buffer */
} CircularBuffer;
/**< Init Circular Buffer */
CircularBuffer* CircularBufferInit(CircularBuffer** pQue, int size)
{
int sz = size*sizeof(KeyType)+sizeof(CircularBuffer);
*pQue = (CircularBuffer*) malloc(sz);
if(*pQue)
{
printf("Init CircularBuffer: keys[%d] (%d)\n", size, sz);
(*pQue)->size=size;
(*pQue)->writePointer = 0;
(*pQue)->readPointer = 0;
}
return *pQue;
}
int main(int argc, char *argv[])
{
CircularBuffer* que;
KeyType a = 101;
int isEmpty, i;
CircularBufferInit(&que, BUFFER_SIZE);
...
}
這裏有幾個問題:
Q1>爲什麼代碼使用下面一行定義變量鍵?
KeyType keys[0]; /**< Element of circular buffer */
Q2>爲什麼代碼計算所分配的緩衝區的大小如下:
int sz = size*sizeof(KeyType)+sizeof(CircularBuffer);
Q3>爲什麼pQue指向比環形緩衝區的尺寸大的緩衝器,但仍然可以 直接指它的成員?
(*pQue)->size=size;
(*pQue)->writePointer = 0;
(*pQue)->readPointer = 0;
非常感謝:) – q0987