C:当指针类型之间没有铸造不确定的行为? [英] C: When is casting between pointer types not undefined behavior?
问题描述
作为一个初来乍到C,我感到困惑铸造一个指针时,实际上是确定。
As a newcomer to C, I'm confused about when casting a pointer is actually OK.
据我了解,你可以pretty多施放任何指针类型到任何其他类型,编译器将让你做到这一点。例如:
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:
- 您可以施放和从
无效*
自由(?) - 您可以施放和从
的char *
自由(?)
- you can cast to and from
void*
freely (?) - you can cast to and from
char*
freely (?)
(至少我已经看到了它在code ...)。
(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指针,在<一个href=\"http://c0x.coding-guidelines.com/6.3.2.3.html\">http://c0x.coding-guidelines.com/6.3.2.3.html ),但并没有真正了解它,除了对位无效*
。
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:的
只是为了澄清:我只是明确地询问正常的指针,即的不的有关函数指针。我认识到,铸造函数指针的规则是非常严格的。正如我没关系事实上,我已经询问了:-):<一href=\"http://stackoverflow.com/questions/2118889/what-happens-if-i-cast-a-function-pointer-changing-the-number-of-parameters\">What如果发生我投一个函数指针,改变参数的数量
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
推荐答案
基本上是:
- 在
T *
可自由转换到无效*
,然后再返回(其中T *
不是一个函数指针),你会得到原来的指针。 - 在
T *
可自由转换到U *
,然后再返回(其中T *
和U *
不是函数指针),你会得到原来的指针,如果对齐要求是相同的。如果不是,该行为是不确定的。 - 一个函数指针可以自由转换成任何其他函数指针类型,然后再返回,你会得到原始指针。
- a
T *
may be freely converted to avoid *
and back again (whereT *
is not a function pointer), and you will get the original pointer. - a
T *
may be freely converted to aU *
and back again (whereT *
andU *
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 *
(非函数指针)总是满足了字符对齐要求*
。
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屋!