[英]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. 通过使用
head->coord
,我已经成功地设法仅访问结构的x字段,从我可以看出这就是我的代码的问题。 I'm already on the first field of the first struct so I can't access x/y because of that. 我已经在第一个结构的第一个字段上,因此我无法访问x / y。
You did not initialize the coord variable so you shoud malloc some space for that too. 您没有初始化coord变量,因此也应该为此分配一些空间。
head->coord = malloc( sizeof (COORD) );
But in this case it might be best to put COORD in NOD instead of referencing to it! 但是在这种情况下,最好将COORD置于NOD而不是引用它!
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
. 您尚未初始化
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. 您还应该检查
malloc()
的返回值是否失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.