0

基本的に、構造体ポインターの配列を作成しようとしています。これらのポインターのそれぞれは、同じ構造体配列の別の要素、つまり BLOCKS[2] を指すと想定されています。

これが私がこれまでやってきたことです。

typedef struct bb {
      ..
      ..
      ..
    struct bb **successor;
} BLOCK;

BLOCK BLOCKS[10];

struct bb **A = malloc(sizeof(struct bb*)*5);        //create an array of pointers of type struct bb, 5 units i.e A[0]->A[4]. 

BLOCKS[0].successors = A                            //just assigning

さて......ポインター配列の最初の要素 A を別の構造体に割り当てるにはどうすればよいでしょうか?

私は試した:

A[0] = &BLOCKS[6];

正常にコンパイルされますが、セグフォルトが発生します。

4

2 に答える 2

1

これを試しましたか:

typedef struct bb {
      ..
      ..
      ..
    struct bb *successor;
} BLOCK;

BLOCK BLOCKS[10];

struct bb *A = malloc(sizeof(struct bb)*5);        //create an array of pointers of
type struct bb, 5 units i.e A[0]->A[4]. 

BLOCKS[0].successors = A[0];

それをすばやく見た後、**は*にレンダリングされるはずであり、mallocは5つの構造のサイズではなく、この構造への5つのポインターのサイズのメモリを予約しているためです。

于 2012-05-21T12:03:24.437 に答える
0

質問からの引用: 私は基本的に、構造体ポインターの配列を作成しようとしています。

構造体ポインタの配列は

BLOCK *ptrBlockArr[10]; //This an array of size 10, which can store 10 pointers to the structure BLOCK

これらはポインタであるため、各要素にメモリを割り当てます。これは次のように行う必要があります

for(int i=0; i<10; i++)
{
   ptrBlockArr[i] = (BLOCK *)malloc(sizeof(BLOCK));
}

質問も含まれています:これらのポインターのそれぞれは、同じ構造体配列の別の要素を指すことになっています。これは次のように行うことができます

for(int i=0; i<9; i++) // Run the loop till the last but one element
{
  ptrBlockArr[i]->successor = ptrBlockArr[i+1];
}
//Assign the last's element's sucessor as the first element. This will make it circular. Check if this is your intention
ptrBlockArr[9]->successor = ptrBlockArr[0]

あなたの構造successorではstruct bb**であることに注意してくださいstruct bb*

また、コードを最適化して、上で示した 2 つのループを 1 つのループに結合することもできます。自分で学習して実装するのはあなたに任せます。

于 2012-05-21T12:24:42.807 に答える