[英]Assigning the value of an union containing structures to NULL in c programming
I have a union and 2 structures in the following format and I need to set one of them to NULL. 我有一个并集和2个结构,采用以下格式,我需要将其中之一设置为NULL。 For example m = NULL or t = NULL; 例如m = NULL或t = NULL;
typedef struct
{
char *population;
char *area;
} metropolitan;
typedef struct
{
char *airport;
char *type;
} tourist;
typedef union
{
tourist t;
metropolitan m;
} ex;
First of all, the members of your union are not pointers, so it doesn't make all that much sense setting the value to NULL
. 首先,联合的成员不是指针,因此将值设置为NULL
并没有多大意义。
Second, the way a union works is that if you set one of the members, you set the others as well. 其次,联合的工作方式是,如果您设置一个成员,那么您也将设置其他成员。 More precisely, all members of a union have the address, but different types. 更准确地说,工会的所有成员都有住址,但类型不同。 Ie the different types gives you a way to interpret the same area in memory as multiple types at once. 即,不同类型为您提供了一种将内存中的同一区域一次解释为多种类型的方法。
To differentiate from a strutct: 区分结构:
struct a {
unsigned b;
char *c;
};
In this case, the appropriate number of bytes are allocated for each of the fields a
and s
, one after the other. 在这种情况下,为字段a
和s
每个字段分配了适当数量的字节,一个接一个。
union a {
unsigned b;
char *c;
};
Here, the values of b
and c
are stored in the same address. 此处, b
和c
的值存储在同一地址中。 Ie if you're setting ab
to 0
, a readout from ac
would give NULL
(numeric 0x0
). 即,如果将ab
设置为0
,则从ac
读取的NULL
将为NULL
(数字0x0
)。
With unions you need to tell them apart. 对于工会,您需要区别对待。
So define a structure thus: 因此定义一个结构:
typedef enum { MET, TOURIST} Chap;
typedef struct {
Chap human;
union {
tourist t;
metropolitan m;
}
} Plonker;
Then you know what is what an then set the appropriate values 然后,您知道什么是什么,然后设置适当的值
ie 即
Plonker p;
p.human = MET;
p.m.population = NULL;
... etc
Since tourist
and metropolitan
are struct
s, you cannot assign NULL
to them. 由于tourist
和metropolitan
是struct
,因此您不能为其分配NULL
。
But, if you declare like 但是,如果您声明像
typedef union
{
tourist* t;
metropolitan* m;
} ex;
you can do 你可以做
ex e;
e.t=NULL; //which makes e.m=NULL as well
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.