当我们覆盖 C 中的联合字段时发生了什么?
What happened when we override union fields in C?
我正在阅读用于在 C 中匹配正则表达式的 Thompson algorithm 的实现。我看到了这段代码:
typedef union Ptrlist Ptrlist;
/*
* Since the out pointers in the list are always
* uninitialized, we use the pointers themselves
* as storage for the Ptrlists.
*/
union Ptrlist
{
Ptrlist *next;
State *s;
};
/* Create singleton list containing just outp. */
Ptrlist*
list1(State **outp)
{
Ptrlist *l;
l = (Ptrlist*)outp;
l->next = NULL;
return l;
}
但据我了解,在 union
类型中,所有字段共享相同的内存。那么为什么我们可以在转换 l=(Ptrlist*)outp;
之后设置 l->next=NULL
因为这样做,我们将该内存位置设置为 NULL
并且 l
将变为 NULL
?
But as I understand, in union
type, all fields share the same memory.
是的。
So why can we set l->next=NULL
after casting l=(Ptrlist*)outp
; because
by doing that, we set that memory location to NULL
and l
will become
NULL
?
没有
您似乎混淆了 l
, 指向 和 PtrList
的指针,以及它指向的 PtrList
对象。 l->next
指定与 l
不同的对象,尽管两者的类型都是 PtrList *
。设置前者的值不影响后者的值
我正在阅读用于在 C 中匹配正则表达式的 Thompson algorithm 的实现。我看到了这段代码:
typedef union Ptrlist Ptrlist;
/*
* Since the out pointers in the list are always
* uninitialized, we use the pointers themselves
* as storage for the Ptrlists.
*/
union Ptrlist
{
Ptrlist *next;
State *s;
};
/* Create singleton list containing just outp. */
Ptrlist*
list1(State **outp)
{
Ptrlist *l;
l = (Ptrlist*)outp;
l->next = NULL;
return l;
}
但据我了解,在 union
类型中,所有字段共享相同的内存。那么为什么我们可以在转换 l=(Ptrlist*)outp;
之后设置 l->next=NULL
因为这样做,我们将该内存位置设置为 NULL
并且 l
将变为 NULL
?
But as I understand, in
union
type, all fields share the same memory.
是的。
So why can we set
l->next=NULL
after castingl=(Ptrlist*)outp
; because by doing that, we set that memory location toNULL
andl
will becomeNULL
?
没有
您似乎混淆了 l
, 指向 和 PtrList
的指针,以及它指向的 PtrList
对象。 l->next
指定与 l
不同的对象,尽管两者的类型都是 PtrList *
。设置前者的值不影响后者的值