的printf(QUOT;%P")和铸造(无效*) [英] printf("%p") and casting to (void *)
问题描述
在最近的问题,有人提到,与打印printf的指针值时,调用者必须转换指针为void *,像这样:
In a recent question, someone mentioned that when printing a pointer value with printf, the caller must cast the pointer to void *, like so:
int *my_ptr = ....
printf("My pointer is: %p", (void *)my_ptr);
有关我的生活我想不出为什么。我发现<一个href=\"http://stackoverflow.com/questions/7290923/when-printf-is-an-address-of-a-variable-why-use-void\">this问题时,这几乎是相同的。这个问题的答案的问题是正确的 - 这解释了整数和指针不一定相同长度
For the life of me I can't figure out why. I found this question, which is almost the same. The answer to question is correct - it explains that ints and pointers are not necessarily the same length.
这是当然的,真实的,但是当我的已的有一个指针,就像上面的例子中,我为什么要自投为int *
到无效*
?当从一个void *不同的一个int *?事实上,当确实(无效*)my_ptr
产生的任何机器code这是不同于简单的 my_ptr
?
This is, of course, true, but when I already have a pointer, like in the case above, why should I cast from int *
to void *
? When is an int * different from a void *? In fact, when does (void *)my_ptr
generate any machine code that's different from simply my_ptr
?
更新:
多懂行反应援引的标准,并称传递错误的类型可能会导致不确定的行为。怎么样?我期待的printf(%P,为(int *)PTR)
和的printf(%P(无效*)PTR)
来产生完全相同的堆栈帧。当将两个调用生成不同的堆栈帧?
UPDATE:
Multiple knowledgeable responders quoted the standard, saying passing the wrong type may result in undefined behavior. How? I expect printf("%p", (int *)ptr)
and printf("%p", (void *)ptr)
to generate the exact same stack-frame. When will the two calls generate different stack frames?
推荐答案
在C语言中所有指针类型都在重新presentation可能不同。所以,是的,为int *
是不同的void *
。一个真实的平台,可以说明这种差异可能很难(甚至不可能)找到,但在概念层次上的差异仍然存在。
In C language all pointer types are potentially different in representation. So, yes, int *
is different from void *
. A real-life platform that would illustrate this difference might be difficult (or impossible) to find, but at the conceptual level the difference is still there.
在换句话说,在一般的情况下,不同的指针类型在重新presentation不同。 为int *
是不同的void *
,不同于双*
。该平台使用相同的重新presentation为事实上无效*
和为int *
无非是多巧合的是,就C语言而言。
In other words, in general case different pointer types are different in representation. int *
is different from void *
and different from double *
. The fact that your platform uses the same representation for void *
and int *
is nothing more than a coincidence, as far as C language is concerned.
语言指出,一些指针类型都需要有相同的再presentations,其中包括无效*
与的char *
,指向不同的结构类型,或者说,为int *
和 const int的*
。但这些都是从一般规则公正的例外情况。
The language states that some pointer types are required to have identical representations, which includes void *
vs. char *
, pointers to different struct types or, say, int *
and const int *
. But these are just exceptions from the general rule.
这篇关于的printf(QUOT;%P&QUOT;)和铸造(无效*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!