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 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.