Alex Postolache Alex Postolache - 2 months ago 21
C Question

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.

usr usr
Answer

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.

Comments