2014-11-04 178 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