结构 C 中的双重取消引用
Double Dereference in struct C
我有以下代码。看来阅读顺序是错误的。有帮助吗?
#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;
}
我已经通过使用 head->coord
成功地只访问了结构的 x 字段,据我所知,这是我的代码的问题。我已经在第一个结构的第一个字段上,因此我无法访问 x/y。
您还没有初始化head->coord
。取消引用未初始化的指针会导致 undefined behaviour。您需要执行以下操作:
head->coord = malloc( sizeof (COORD) );
您还应该检查 malloc()
的 return 值是否失败。
您没有初始化 coord 变量,因此您也应该为此 malloc 一些 space。
head->coord = malloc( sizeof (COORD) );
但在这种情况下,最好将 COORD 放在 NOD 而不是引用它!
所以:
typedef struct nod{
COORD coord;
struct nod *urm;
}NOD;
只有当您要大量交换对象或它是一个更复杂的对象时,您才应该真正指向它。
我有以下代码。看来阅读顺序是错误的。有帮助吗?
#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;
}
我已经通过使用 head->coord
成功地只访问了结构的 x 字段,据我所知,这是我的代码的问题。我已经在第一个结构的第一个字段上,因此我无法访问 x/y。
您还没有初始化head->coord
。取消引用未初始化的指针会导致 undefined behaviour。您需要执行以下操作:
head->coord = malloc( sizeof (COORD) );
您还应该检查 malloc()
的 return 值是否失败。
您没有初始化 coord 变量,因此您也应该为此 malloc 一些 space。
head->coord = malloc( sizeof (COORD) );
但在这种情况下,最好将 COORD 放在 NOD 而不是引用它!
所以:
typedef struct nod{
COORD coord;
struct nod *urm;
}NOD;
只有当您要大量交换对象或它是一个更复杂的对象时,您才应该真正指向它。