打印函數名,函數名前加n個*爲什麼結果相同?


程序:
#include <stdio.h>
void func()
{
int i = 1;
}
int main()
{
printf("%p\n",main);
printf("%p\n",*main);
printf("%p\n",**main);
printf("%p\n",***main);
printf("%p\n",func);
printf("%p\n",*func);
printf("%p\n",**func);
printf("%p\n",***func);
return 0;
}
結果:
eagle@eagle-QJC4:~$ ./a.out 
4195652
4195652
4195652
4195652
4195638
4195638
4195638
4195638
以下答案來自http://blog.chinaunix.net/uid-10314004-id-2964074.html
C語言中的函數是一種function-to-pointer方式,即對於函數,要將其轉化成指針類型的.
ptr是函數指針類型,則*ptr是該指針所指向的函數,而由於函數自身又轉化成指針了,所以說*ptr又轉化成了ptr這種函數指針類型,因此,前面無論有多少個*號,最後都是對這個函數的調用.

下面的答案來自   @fefe82 的回答 @fefe82
C11 draft n1570
6.3.2.1 Lvalues, arrays, and function designators
4 A function designator is an expression that has function type. Except when it is the
operand of the sizeof operator, the _Alignof operator, or the unary & operator, a
function designator with type ‘‘function returning type’’ is converted to an expression that
has type ‘‘pointer to function returning type’’
.

6.5.3.2 Address and indirection operators
The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator; if it points to an object, the result is an lvalue designating the
object.
 If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an
invalid value has been assigned to the pointer, the behavior of the unary * operator is
undefined.

function designator 會自動轉換成 pointer to function, 加一個 * 之後變成 function designator ,然後又自動轉換成 pointer to function,周而復始,無論你加多少 * ,最後拿到的還是一個 pointer to function 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章