开发者

Flexible array of pointers to char in a struct

I'm trying to implement a ring buffer with the following struct

/*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[];
};

Then I use the following function to create a string buffer:

 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++)
开发者_如何学C        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;
   }

I call this function in main:

 struct rb *newRB = (struct rb*)create(100);

However, I have problem right at the step allocating memory for struct. In the debugging mode, I can see the value of head, tail, count, were assigned very strange large numbers but not 0. And program hangs after this very first step without throwing me any exception.

Could someone help me explain this problem please? How can I fix it?


I have a hard time reading your code, but from what I gather, you probably want to do something along the lines of:

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 will make sure the contents of the allocated space are set to zero. Also, just allocating an additional n*sizeof(char*) with your first call to malloc seems fishy.


The following should be a shorter way to do the same:

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

This sets all the allocated space to 0 and then sets the size field correctly.


Thank you guys a lot for helping. I made it work with char** and it's definitely much easier than working flexibly array member.

However, I wonder, when you have char **array; you can use array[i] and it will give you a pointer to char. Why if we have char *array; we cannot use array[i] to get a char?

Hope I make myself clear enough here.

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜