0

何らかの理由で、ここでセグメンテーション違反が発生しています。理由がわかりません。何か助けはありますか?

typedef struct gw_struct{
    int pop;
    int col;
    int row;
    struct district ***gw;
    struct person **people;
};

typedef struct gw_struct *GW;

その後、関数で...

GW world;
struct district ***array = malloc(nrows*sizeof(struct district**));
    int i, j;
for (i = 0; i < nrows; i++)
{
    array[i] = malloc(ncols*sizeof(struct district*));
    for (j = 0; j<ncols; j++)
    {
            array[i][j] = malloc(sizeof(struct district));
    }
}   

world->gw = array; //this is the line that gives the seg fault
4

2 に答える 2

2

あなたのコードは初期化されていないworldため、その行で逆参照しようとすると、おそらくどこかの雑草を指しています。変数を使用する前に、必ず変数を初期化してください。

于 2013-03-11T05:51:08.543 に答える
-1

問題は最初の行GW world;にあります。これはメモリ内で適切に参照されていません。

これはうまくいくはずです:

GW *world;
struct district ***array = malloc(nrows*sizeof(struct district**));
    int i, j;
for (i = 0; i < nrows; i++)
{
    array[i] = malloc(ncols*sizeof(struct district*));
    for (j = 0; j<ncols; j++)
    {
            array[i][j] = malloc(sizeof(struct district));
    }
}   

world->gw = array; //this is the line that gives the seg fault

World 変数の宣言はポインターである必要があります。これにより、メモリ内の初期化された構造体が適切に参照され、割り当てを行うことができます。

于 2014-10-30T02:35:54.963 に答える