c -无法解释的分割故障



由于某种原因,我在这里得到一个分段错误。我也不知道为什么。任何帮助吗?

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

您的代码没有初始化world,因此当您试图在该行解引用它时,它可能会指向杂草的某个地方。

您的问题在第一行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变量声明需要是一个指针,这将正确地引用你在内存中初始化的结构,并允许你进行赋值。

最新更新