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 回答