我正在尝试使用以下结构实现环形缓冲区
/*head, tail are indexes of the head and tail of ring buffer
*count is the number of elements; size is the max size of buffer
*rbArray is an array to pointer of char used to store strings
*/
struct rb{
int head;
int tail;
int count;
int size;
char *rbArray[];
};
然后我使用以下函数创建一个字符串缓冲区:
struct rb *create(int n){
/*allocate memory for struct*/
struct rb *newRb = (struct rb*)malloc(sizeof(struct rb)+ n*sizeof(char *));
assert(newRb);
int i;
for(i=0;i<n;i++)
newRb->rbArray[i] = NULL;
/*put head and tail at the beginning of array
initialize count, set max number of elements*/
newRb->head = 0;
newRb->tail = 0;
newRb->count = 0;
newRb->size = n;
return newRb;
}
我在 main 中调用这个函数:
struct rb *newRB = (struct rb*)create(100);
但是,我在为结构分配内存的步骤中遇到了问题。在调试模式下,我可以看到 head、tail、count 的值被分配了非常奇怪的大数字,但不是 0。在第一步之后程序挂起,没有给我任何异常。
有人可以帮我解释一下这个问题吗?我该如何解决?