2014-11-04 307 views
-2

如何定義名爲scary的變量,該變量是指向一個函數的指針,該函數將單個指針類型的arg指向double並返回指向short的指針?指向函數的指針

這是正確的嗎? short* (*scary)(double*)

+1

如果只有有一種方法來測試這個... – 2014-11-04 14:11:11

+4

[是](http://cdecl.ridiculousfish.com/?q=short*+%28*scary%29%28double*%29) – 2014-11-04 14:11:34

+0

所有我掃描說你不應該這樣做。 – ha9u63ar 2014-11-04 14:12:00

回答

1

你應該真正用Google搜索擺在首位「函數指針ç」,但我相信你的問題是你有什麼已經研究確認。

是的,這是正確的,採取以下爲例:

short global = 2; 
short * ptr_to_global = &global; 

short* scary_fun(double* ptr) { 
    return ptr_to_global; 
} 

int main(void) { 
    double val = 22.0; 
    double *ptr_to_val = &val; 
    short* (*scary)(double*); 
    scary = &scary_fun; 
    printf("%d", *(scary(ptr_to_val))); // Prints "2" 
    return 0; 
} 

Example

1
  scary       -- scary 
     *scary       -- is a pointer to 
     (*scary)(   )   -- a function on 
     (*scary)(  arg)   -- parameter arg 
     (*scary)(  *arg)   --  is a pointer to 
     (*scary)(double *arg)   --  type double 
     *(*scary)(double *arg)   -- returning a pointer to 
short *(*scary)(double *arg)   -- type short 

下標[]和函數調用()運營商有超過一元*更高的優先級,所以:

T *a[N] -- a is an N-element array of pointer to T 
T (*a)[N] -- a is a pointer to an N-element array of T 
T *f()  -- f is a function retunring pointer to T 
T (*f)() -- f is a pointer to a function returning T