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);
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.
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
?
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?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…