1

以下のコードでわかるように、親と子の 2 つの構造があります。親構造体には、子型のポインターの配列があります。プログラムが for ループに入ると、セグメンテーション エラーが発生します。私のコードに何か問題がありますか? 角括弧を使用したくない理由は、子型のポインター パラメーターを受け取る関数があり、& を使用せずにすべての子ポインターをその関数に渡したいからです。

任意の助けをいただければ幸いですありがとう

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
   int id;
} child;

typedef struct {
   child** c;
} parent;

int main(int argc, char **argv) {
    int number_of_children = 5;

parent* p = (parent*)malloc(sizeof(parent));

p -> c = (child **) malloc(number_of_children * sizeof(child*));

int i;
for(i=0; i<number_of_children; i++)
    p -> c[i] -> id = i;
}
4

2 に答える 2

5

子ポインター テーブルを正しく割り当てていますが、子を割り当てていません。

int i
for(i = 0; i < number_of_children; ++i) {
    p->c[i] = (child *) malloc(sizeof(child));
    p -> c[i] -> id = i
}
于 2013-04-15T19:13:47.613 に答える
1

テストされていませんが、次の行に沿ったものである必要があります。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
   int id;
} child;

typedef struct {
   child** c;
} parent;

int main(int argc, char **argv) {
    const int number_of_children = 5;

    parent* p = malloc(sizeof(parent));
    if(p == NULL) halt_and_catch_fire();

    p->c = malloc(number_of_children * sizeof(child*));
    if(p->c == NULL) halt_and_catch_fire();    

    for(int i=0; i<number_of_children; i++)
    {
        p->c[i] = malloc(sizeof(child));
        if(p->c[i] == NULL) halt_and_catch_fire();

        p->c[i]->id = i;
    }

    // free() *everything* allocated
}

ご覧のとおり、最も内側のオブジェクトを複数割り当てていないため、セグメント化されたポインターツーポインターのものを割り当てようとしていますが、これは明らかに必要ではありません。多次元配列を作成しようとしている場合は、セグメント化された混乱を作成しないでください。代わりに、このようにしてください

于 2013-04-15T19:21:37.793 に答える