是否所有指针都保证通过 void * 正确往返?
Are all pointers guaranteed to round-trip through void * correctly?
是否保证在 C 中,任何指针类型都可以成功往返 void *
?
也就是说,像下面这样的东西保证有效:
typedef struct {
...
} A;
A *p = ...;
void *v = p;
A *p2 = v;
// use p2 here
无论A
是什么类型?
对象指针确实可以是 round-tripped 到 void*
。来自 C11 6.3.2.3 第 1 段:
A pointer to void may be converted to or from a pointer to any object type. A pointer to
any object type may be converted to a pointer to void and back again; the result shall
compare equal to the original pointer.
请注意,相反的方向是不正确的,当您将 void 指针转换为某个对象指针并返回时,您不能保证与开始时的值相同。
另请注意,函数指针不是;但是,所有函数指针类型相互 round-trippable:第 8 段说:
A pointer to a function of one type may be converted to a pointer to a function of another
type and back again; the result shall compare equal to the original pointer.
此外,对象指针之间也是round-trippable(不涉及 void 指针),受某些限制,第 7 段:
A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned) for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.
是否保证在 C 中,任何指针类型都可以成功往返 void *
?
也就是说,像下面这样的东西保证有效:
typedef struct {
...
} A;
A *p = ...;
void *v = p;
A *p2 = v;
// use p2 here
无论A
是什么类型?
对象指针确实可以是 round-tripped 到 void*
。来自 C11 6.3.2.3 第 1 段:
A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
请注意,相反的方向是不正确的,当您将 void 指针转换为某个对象指针并返回时,您不能保证与开始时的值相同。
另请注意,函数指针不是;但是,所有函数指针类型相互 round-trippable:第 8 段说:
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.
此外,对象指针之间也是round-trippable(不涉及 void 指针),受某些限制,第 7 段:
A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned) for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.