1

次の構造体でリングバッファを実装しようとしています

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

私はこの関数をメインで呼び出します:

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

しかし、構造体にメモリを割り当てるステップで問題が発生します。デバッグモードでは、head、tail、countの値に非常に奇妙な大きな数値が割り当てられていますが、0は割り当てられていません。この最初のステップの後、プログラムは例外をスローせずにハングします。

誰かが私にこの問題を説明するのを手伝ってもらえますか?どうすれば修正できますか?

4

3 に答える 3

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は、割り当てられたスペースの内容がゼロに設定されていることを確認します。n*sizeof(char*)また、 mallocへの最初の呼び出しで追加を割り当てるだけでは、怪しいようです。

于 2010-09-15T07:45:15.910 に答える
0

以下は、同じことを行うためのより短い方法です。

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

これにより、割り当てられたすべてのスペースが0設定され、sizeフィールドが正しく設定されます。

于 2010-09-15T12:07:28.323 に答える
0

助けてくれてありがとう。char** で動作するようにしましたが、柔軟に配列メンバーを動作させるよりもはるかに簡単です。

しかし、いつ char **array; があるのだろうか。array[i] を使用すると、char へのポインタが得られます。char *array; があるのはなぜですか。array[i] を使用して char を取得することはできませんか?

ここで十分に明確になることを願っています。

ありがとう

于 2010-09-15T15:23:33.927 に答える