我正在尝试使用以下结构实现环形缓冲区
/*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);
但是,我在为 struct 分配内存的步骤中遇到了问题。在 Debug模式下,我可以看到 head、tail、count 的值被分配了非常奇怪的大数字,但不是 0。程序在这第一步后挂起,没有抛出任何异常。
有人可以帮我解释一下这个问题吗?我该如何解决?
最佳答案
我很难阅读您的代码,但根据我收集到的信息,您可能想按照以下方式做一些事情:
struct rb *create(int n)
{
struct rb newRb = calloc(1, sizeof(struct rb));
newRb->rbArray = calloc(n, sizeof(char*));
newRb->count = n;
return newRb;
}
calloc 将确保分配空间的内容设置为零。此外,在第一次调用 malloc 时分配额外的 n*sizeof(char*)
似乎很可疑。
关于c - 指向结构中 char 的灵活指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3715570/