是否保证所有指针都正确地通过 void * 往返? [英] Are all pointers guaranteed to round-trip through void * correctly?

查看:38
本文介绍了是否保证所有指针都正确地通过 void * 往返?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中是否保证任何指针类型都可以成功地通过 void * 往返?

Is it guaranteed, in C, that any pointer type can round-trip through void * successfully?

也就是说,以下内容保证有效:

That is, something like the following guaranteed to work:

typedef struct {
...
} A;

A *p = ...;
void *v = p;
A *p2 = v;
// use p2 here

不管A的类型是什么?

推荐答案

对象指针确实可以通过 void* 来回传递.来自 C11 6.3.2.3 第 1 段:

Object pointers can indeed be round-tripped through void*. From C11 6.3.2.3 paragraph 1:

指向 void 的指针可以与指向任何对象类型的指针相互转换.一个指向任何对象类型都可以转换为指向 void 的指针,然后再返回;结果应比较等于原始指针.

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 指针转换为某个对象指针并返回时,不能保证与开始时的值相同.

Note that the opposite direction is not true, when you convert a void pointer to some object pointer and back you are not guaranteed the same value as what you started with.

还要注意,这对于函数指针来说不是;然而,所有函数指针类型都是相互可往返的:第 8 段说:

Note also that this is not true of function pointers; however, all function pointer types are mutually round-trippable: Paragraph 8 says:

指向一种函数的指针可以转换为指向另一种函数的指针再次输入并返回;结果应与原始指针相等.

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.

此外,对象指针在它们之间也是可往返的(不涉及空指针),受一些限制,第 7 段:

Moreover, object pointers are also round-trippable among themselves (not involving void pointers), subject to some constraints, by paragraph 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.

这篇关于是否保证所有指针都正确地通过 void * 往返?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆