c - 指向结构中 char 的灵活指针数组

标签 c arrays struct malloc member

我正在尝试使用以下结构实现环形缓冲区

/*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/

相关文章:

php mysql在不同服务器上处理数据

c++ - 搜索已排序的 float 数组

c - 具有多个数组的结构,其大小在执行时定义

arrays - 通过结构和数组填充 Tableview

C 结构数据在迭代循环外无法保持一致

c++ - 管理 wiimote 的最佳图书馆是什么?

c - 为什么在二维数组中 a 和 *a 指向相同的地址?

c - 这可能吗? [指向字符数组 C 的指针]

c - BZip2 解压非文件数据时不会出现错误?

c - 为什么函数参数动态分配的内存在退出函数时会丢失?