当前位置: 动力学知识库 > 问答 > 编程问答 >

Double Dereference in struct C

问题描述:

I have the following code. It seems the reading sequence is wrong. Any help?

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

typedef struct punct{

int x;

int y;

}COORD;

typedef struct nod{

COORD *coord;

struct nod *urm;

}NOD;

int main()

{

NOD *head= malloc( sizeof(NOD) );

scanf("%d", &head->coord->x );

scanf("%d", &head->coord->y );

printf("%d, %d", head->coord->x , head->coord->y);

return 0;

}

I have successfully managed to access only the x field of the struct by using head->coord, and from what I can tell that's the issue with my code. I'm already on the first field of the first struct so I can't access x/y because of that.

网友答案:

You haven't initialized head->coord. Dereferencing uninitialized pointers result in undefined behaviour. You need to do something like:

  head->coord = malloc( sizeof (COORD) );

You should also check the return value of malloc() for failures.

网友答案:

You did not initialize the coord variable so you shoud malloc some space for that too.

head->coord = malloc( sizeof (COORD) );

But in this case it might be best to put COORD in NOD instead of referencing to it!

So:

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

You should only really make a pointer to it when you are going to swap the object a lot or when its a more complex object.

分享给朋友:
您可能感兴趣的文章:
随机阅读: