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

查看:118
本文介绍了什么时候在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?

Edit:

我尝试研究C标准(在 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 * 不是函数指针),如果对齐,则将获得原始指针要求是相同的。如果不是,则行为是不确定的。

  • 可以将函数指针自由转换为任何其他函数指针类型,然后再次返回,则将获得原始指针。

  • 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天全站免登陆