何时在指针类型之间进行转换而不是 C 中的未定义行为? [英] When is casting between pointer types not undefined behavior in C?

查看:19
本文介绍了何时在指针类型之间进行转换而不是 C 中的未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 C 的新手,我很困惑什么时候转换指针实际上是可以的.

As a newcomer to C, I'm confused about when casting a pointer is actually OK.

据我所知,您几乎可以将任何指针类型转换为任何其他类型,编译器会让您这样做.例如:

As I understand, you can pretty much cast any pointer type to any other type, and the compiler will let you do it. For example:

int a = 5;
int* intPtr = &a;
char* charPtr = (char*) intPtr; 

然而,通常这会调用未定义的行为(尽管它恰好适用于许多平台).这就是说,似乎有一些例外:

However, in general this invokes undefined behavior (though it happens to work on many platforms). This said, there seem to be some exceptions:

  • 你可以自由地在void*之间进行转换(?)
  • 您可以自由地在 char* 之间进行转换 (?)
  • you can cast to and from void* freely (?)
  • you can cast to and from char* freely (?)

(至少我在代码中见过它......).

(at least I've seen it in code...).

那么哪些指针类型之间的转换不是在 C 中的未定义行为?

So which casts between pointer types are not undefined behaviour in C?

我尝试查看 C 标准(6.3.2.3 指针"部分,位于 http://c0x.coding-guidelines.com/6.3.2.3.html ),但并没有真正理解它,除了关于 void* 的一点.

I tried looking into the C standard (section "6.3.2.3 Pointers", at http://c0x.coding-guidelines.com/6.3.2.3.html ), but didn't really understand it, apart from the bit about void*.

Edit2:

只是为了澄清:我明确地只询问普通"指针,即不是关于函数指针.我意识到强制转换函数指针的规则非常严格.事实上,我已经问过了:-): 如果我转换一个函数指针,改变参数的数量会发生什么

Just for clarification: I'm explicitly only asking about "normal" pointers, i.e. not about function pointers. I realize that the rules for casting function pointers are very restrictive. As I matter of fact, I've already asked about that :-): What happens if I cast a function pointer, changing the number of parameters

推荐答案

基本上:

  • a T * 可以自由转换为 void * 并再次返回(其中 T * 不是函数指针),并且您将获得原始指针.
  • a T * 可以自由转换为 U * 并再次返回(其中 T *U *code> 不是函数指针),如果对齐要求相同,您将获得原始指针.如果不是,则行为未定义.
  • 一个函数指针可以自由地转换为任何其他函数指针类型,然后再返回,你将得到原始指针.
  • a T * may be freely converted to a void * and back again (where T * is not a function pointer), and you will get the original pointer.
  • a T * may be freely converted to a U * and back again (where T * and U * are not function pointers), and you will get the original pointer if the alignment requirements are the same. If not, the behaviour is undefined.
  • a function-pointer may be freely converted to any other function-pointer type and back again, and you will get the original pointer.

注意: T *(对于非函数指针)总是满足char *的对齐要求.

Note: T * (for non-function-pointers) always satisfies the alignment requirements for char *.

重要提示:这些规则都没有说明任何关于将T *转换为U会发生什么的事情* 然后尝试取消引用它.这是标准的一个完全不同的领域.

Important: None of these rules says anything about what happens if you convert, say, a T * to a U * and then try to dereference it. That's a whole different area of the standard.

这篇关于何时在指针类型之间进行转换而不是 C 中的未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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