Alex Postolache Alex Postolache - 1 month ago 8x
C Question

Double Dereference in struct C

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


typedef struct punct{
int x;
int y;

typedef struct nod{
COORD *coord;
struct nod *urm;
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
, 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.

usr usr

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.