close

 

https://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-or-address

根據standard C99 和 C11 (差別在哪?)

The C99 standard (ISO/IEC 9899:1999) says in §7.19.6.1 ¶8:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

(In C11 — ISO/IEC 9899:2011 — the information is in §7.21.6.1 ¶8.)

或Linux printf manual

http://man7.org/linux/man-pages/man3/printf.3.html

回覆者經驗談

It is somewhat open to debate whether you should explicitly convert the pointers with a (void *)cast. It is being explicit, which is usually good (so it is what I do), and the standard says 'the argument shall be a pointer to void'. On most machines, you would get away with omitting an explicit cast. However, it would matter on a machine where the bit representation of a char *address for a given memory location is different from the 'anything else pointer' address for the same memory location. This would be a word-addressed, instead of byte-addressed, machine. Such machines are not common (probably not available) these days, but the first machine I worked on after university was one such (ICL Perq).

 

結論

So, it does seem that explicit casts to void * are strongly advisable for maximum reliability in the code when passing a pointer to a variadic function such as printf(). On POSIX systems, it is safe to cast a function pointer to a void pointer for printing. On other systems, it is not necessarily safe to do that, nor is it necessarily safe to pass pointers other than void * without a cast.

 

arrow
arrow
    文章標籤
    C programming
    全站熱搜

    紅線 發表在 痞客邦 留言(0) 人氣()