无法访问内存和分段错误

时间:2016-09-06 23:07:22

标签: c pointers dynamic struct segmentation-fault

我正在尝试实现两种结构,它们可以正常工作直到一点。

typedef struct punct{
int x;
int y;

} COORD;

typedef struct nod{
COORD *coord;
struct nod *urm;

} NOD;

我认为问题在于我指的是错误的地方:

NOD *crt, *cap, *urm;
crt=(NOD*)malloc(sizeof(NOD));
cap=(NOD*)malloc(sizeof(NOD));
cap->urm=crt;
crt->urm=NULL;


for(i=0;i<n;i++)
{

    NOD *next=(NOD*)malloc(sizeof(NOD));
    next->urm =NULL;
    COORD *coordo = (COORD*)malloc(sizeof(COORD));
    coordo->x=coordonate[i].x; //these are just some elements from an array, they work fine
    coordo->y=coordonate[i].y;
    next->coord=coordo; //here I think is what is causing the problem
    crt->urm=next;

    crt=next;
}

虽然我认为我错过了某些地方,但是当我尝试打印坐标时会出现错误:

 crt=cap->urm;
for(i=0;i<n;i++)
{
    printf("%d %d\n",crt->coord->x,crt->coord->y); //this is where the "Can't acces memory at adress ..."    
error and the segmentation fault appears from. I've tested with the debuger.
    urm=crt->urm;
    crt=urm;
}

我做错了什么?

0 个答案:

没有答案