Pin*_*ade 1 c syntax pointers function-pointers argument-passing
我正在学习C,我来到这个表达式:
void *(*routine)(void *)
Run Code Online (Sandbox Code Playgroud)
我觉得很困惑.也许它是一个指针......指针......指针?
如果我想把这个东西传递给一个函数,我们将如何操纵它?我试图将这个例程构造作为一个参数传递给一个需要void(*)(void)... 的函数但是我真的很遗憾.
Joh*_*ode 27
从最左边的标识符开始,然后解决问题,记住没有带括号的显式分组,[]以及()之前的函数调用bind *,所以
*a[N] 是一个N元素的指针数组(*a)[N] 是指向N元素数组的指针*f() 是一个返回指针的函数(*f)() 是一个指向函数的指针所以,
routine -- routine
*routine -- is a pointer
(*routine)( ) -- to a function
(*routine)(void *) -- taking a single parameter of type void *
*(*routine)(void *) -- returning a pointer
void *(*routine)(void *) -- to void
Run Code Online (Sandbox Code Playgroud)
Lih*_*ihO 14
void *(*routine)(void *);
Run Code Online (Sandbox Code Playgroud)
声明一个指向函数的指针,该函数接受类型的参数void *并返回类型的指针void *
简单的例子:
#include <stdio.h>
void* foo(void* x) {
printf("Hello.");
}
int main(void) {
void *(*routine)(void *);
routine = foo; // assings foo to our function pointer
(*routine)(NULL); // invokes foo using this pointer
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出: Hello.
"如果我想把这个东西传递给一个函数"〜这里是你的例子2:
#include <stdio.h>
void* foo(void* x) {
printf("Hello.");
}
typedef void *(*RoutinePtr)(void *); // alias to make your life easier
void routineInvoker(RoutinePtr routine) {
(*routine)(NULL); // invokes the routine
}
int main(void) {
RoutinePtr routine = foo; // creates a function pointer
routineInvoker(routine); // and passes it to our invoker
return 0;
}
Run Code Online (Sandbox Code Playgroud)