2010-06-14 92 views
3

可能重複:
How does dereferencing of a function pointer happen?函數指針的使用

大家好, 爲什麼這兩個碼給出相同的輸出, 案例1:

#include <stdio.h> 

typedef void (*mycall) (int a ,int b); 
void addme(int a,int b); 
void mulme(int a,int b); 
void subme(int a,int b); 

main() 
{ 
    mycall x[10]; 
    x[0] = &addme; 
    x[1] = &subme; 
    x[2] = &mulme; 
    (x[0])(5,2); 
    (x[1])(5,2); 
    (x[2])(5,2); 
} 

void addme(int a, int b) { 
    printf("the value is %d\n",(a+b)); 
} 
void mulme(int a, int b) { 
    printf("the value is %d\n",(a*b)); 
} 
void subme(int a, int b) { 
    printf("the value is %d\n",(a-b)); 
} 

輸出:

the value is 7 
the value is 3 
the value is 10 

案例2:

#include <stdio.h> 

typedef void (*mycall) (int a ,int b); 
void addme(int a,int b); 
void mulme(int a,int b); 
void subme(int a,int b); 

main() 
{ 
    mycall x[10]; 
    x[0] = &addme; 
    x[1] = &subme; 
    x[2] = &mulme; 
    (*x[0])(5,2); 
    (*x[1])(5,2); 
    (*x[2])(5,2); 
} 

void addme(int a, int b) { 
    printf("the value is %d\n",(a+b)); 
} 
void mulme(int a, int b) { 
    printf("the value is %d\n",(a*b)); 
} 
void subme(int a, int b) { 
    printf("the value is %d\n",(a-b)); 
} 

輸出:

the value is 7 
the value is 3 
the value is 10 
+0

有人編輯並放入代碼形式請 – geshafer 2010-06-14 15:17:58

+1

重複[如何解除函數指針的引用?](http://stackoverflow.com/questions/2795575/how-does-dereferencing-of-a-function-指針 - 發生) – 2010-06-14 15:21:34

回答

5

我會簡化您的問題,以顯示我認爲您想知道的內容。

鑑於

typedef void (*mycall)(int a, int b); 
mycall f = somefunc; 

你想知道爲什麼

(*f)(5, 2); 

f(5.2); 

做同樣的事情。答案是,函數名稱都代表「函數指示符」。從標準:

"A function designator is an expression that has function type. Except when it is the 
operand of the sizeof 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’’." 

當您使用間接運算符*上一個函數指針,即取消引用也是「功能符號」。從標準:

"The unary * operator denotes indirection. If the operand points to a function, the result is 
a function designator;..." 

所以f(5,2)第一規則基本上(*f)(5,2)變。這成爲第二個call to function designated by f with parms (5,2)。結果是f(5,2)(*f)(5,2)做同樣的事情。

+2

認爲你有一個小的錯字,* mycall ---> myfunc – reuscam 2010-06-14 15:55:12

+0

@reuscam:fixed,thanx。 – 2010-06-14 17:39:38

+0

很好的答案和偉大的引用。 – sjsam 2016-06-08 09:30:29

3

因爲無論你用或不用引用操作使用這些函數指針自動解決。

2

你沒有之前函數名

x[0] = addme; 
x[1] = subme; 
x[2] = mulme; 

但是這兩種方式都是有效的使用&。