在C中,是否允许直接从某种类型的指针转换为另一种类型?
假设您从一个 void 指针、一个 char 指针、一个 int 指针或任何您想命名的指针开始。
void *p = // initialized to something here
我们进行类似的转换,
*((int *)((char *)p + 6)) = 5;
这是否意味着我们基本上将 void 指针转换为 char 指针,进行一些算术,将其转换为 int 指针,然后取消引用它以存储 5?
或者我们是否需要先将 char 指针转换回 void 指针,然后才能安全地将其转换为 int 指针?
* 另外,在从 char* 转换为 int* 之前,是否需要在转换之前在某处取消引用?
Let's say you start with a void pointer, or a char pointer, or an int pointer, or whatever you would like to name.
void *p = // initialized to something here
And we do a conversion like
*((int *)((char *)p + 6)) = 5;
Does this mean we are basically casting a void pointer to a char pointer, doing some arithmetic, casting that to an int pointer, and then de-referencing it to store 5?
Or do we need to cast the char pointer back to a void pointer before it is safe to cast it to the int pointer?
* Also, before casting from char* to int*, does there need to be a de-reference somewhere before the conversion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您显示的转换在语法上是有效的 C。通过
void *
类型转换为int *
没有什么区别。它在语义上是否正确取决于
(char *)p + 6
指向的内存是否正确调整大小并对齐以作为int
进行访问。The conversion you have shown is syntactically valid C. Casting through a
void *
type on the way toint *
makes no difference.Whether it is semantically correct depends on whether the memory pointed to by
(char *)p + 6
is correctly sized and aligned for access asint
.在将 char 指针转换为 int 指针之前将其转换回 void 指针并不比将 char 指针转换为 int 指针更好。不过,您必须真正了解自己在做什么才能使其发挥作用,因为您必须处理对齐问题。
Casting a char pointer back to a void pointer before casting it to an int pointer won't be any better than just casting a char pointer to an int pointer. You've got to really know what you are doing to make it work though, because you have to deal with alignment issues.
C 在允许潜在危险的指针类型转换方面比 C++ 宽松得多。它源于 C 的“程序员知道他们在做什么”的哲学。然而,由于类型转换的潜在危险,C++ 引入了三种类型的转换:
static_cast
、dynamic_cast
和reinterpret_cast
。推荐阅读:
C is much more lenient than C++ in allowing potentially dangerous pointer typecasts. It stems from C's "the programmer knows what they're doing" philosophy. However, because of the potential dangers of typecasting, C++ introduces three types of casting,
static_cast
,dynamic_cast
, andreinterpret_cast
.Recommended reading:
从一个指向一种整数类型的指针转换为另一个指向不同整数类型的指针如果导致对齐问题,则属于未定义行为 (C99 6.3.2.3)。如果没有,您可以在它们之间安全地进行转换。
char
是整数类型。(C 标准在这里有点奇怪,指出这是 UB。这应该是实现定义的行为,因为它取决于特定的 CPU 架构并且在许多情况下是安全的。)
在您的具体示例中,它确实是你所描述的意思。其背后的原因可能是:
Casting from a pointer to one integer type, to another pointer to a different integer type is undefined behavior if it leads to alignment issues (C99 6.3.2.3). If it doesn't, you can cast between them safely.
char
is an integer type.(The C standard is a bit weird here, stating that this is UB. This should have been implementation-defined behavior, because it depends on the specific CPU architecture and is safe in many cases.)
In the case of your specific example, it does indeed mean what you describe. The reasons behind it are likely: