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

时间:2010-09-15 07:37:29

标签: 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分配内存的步骤中遇到了问题。在调试模式下,我可以看到head,tail,count的值被分配了非常奇怪的大数而不是0.并且程序在这第一步之后挂起而没有任何异常。

有人可以帮我解释一下这个问题吗?我该如何解决?

3 个答案:

答案 0 :(得分:3)

我很难阅读您的代码,但从我收集的内容来看,您可能希望按照以下方式执行操作:

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*)似乎很可疑。

答案 1 :(得分:0)

以下应该是一种较短的方法:

struct rb *create(int n)
{
    struct rb * newRb = calloc(sizeof(struct rb) + n*sizeof(char*), 1);
    newRb->size = n;    
    return newRb;
}

这会将所有已分配的空间设置为0,然后正确设置size字段。

答案 2 :(得分:0)

非常感谢你们帮忙。我使用了char **,它比使用灵活的数组成员更容易。

然而,我想知道,当你有      char **数组; 你可以使用array [i],它会给你一个指向char的指针。为什么我们有      char * array; 我们不能使用array [i]来获取char?

希望我在这里做得很清楚。

由于