2013-03-11 60 views
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 
+2

你有没有intialise指针世界? – 999k 2013-03-11 05:51:48

回答

2

您的代码不会初始化world,所以想必它指向方向,误入歧途某处当您尝试取消对它的引用在该行。确保在使用它们之前初始化变量。

+0

我改变了初始化,但它仍然不起作用。 – SwiftCore 2013-03-11 05:53:00

+0

现在会发生什么? – 2013-03-11 05:53:58

+0

在同一地点发生Seg故障... – SwiftCore 2013-03-11 05:54:23

-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 

你的世界变量声明必须是一个指针,这将正确引用您的初始化结构在内存中,可以让你让你的任务。

+0

请添加一些细节,为什么您发布此代码,以及它如何帮助解决问题。 – Hamad 2014-10-30 05:34:13