我想初始化一个大小为5的指针数组,这些指针包含指向没有参数的函数的指针,并返回一个int(可以是任何促进这些要求的函数)。
这是我到目前为止尝试但我得到语法错误:
int (*func)() fparr[5] = int (*func)();
这个语法有什么问题?
如果您要提供的函数作为数组的默认内容称为func
,那么
typedef
,考虑:
typedef int (*IntFunc)(void);
IntFunc fparr[5] = { func, func, func, func, func };
或者不太可读的方式,如果你更愿意避免使用typedef
:
int (*fparr[5])(void) = { func, func, func, func, func };
因为你实际上并没有初始化一个函数指针数组...尝试:
int (*fparr[5])(void) = { func1, func2, func3, func4, func5 };
步骤1:
将函数的签名定义为类型FN
:
typedef int (*FN)();
第2步:
使用FN
签名定义5个函数:
int f1(void) { ; }
int f2(void) { ; }
...
第3步:
定义并初始化类型为FN
的5个函数的数组:
FN fparr[5] = {f1,f2,f3,f4,f5}
除此以外:
如果你不想定义一个单独的签名,你可以这样做 - 如前所述 - 所以:
int ((*)fpar []) () = {f1,f2, ...}
如果您在声明时知道数组中的函数数量,则不需要编写5
,编译器会为您分配此内存,如果您在与声明相同的行初始化数组。
好吧,我迟到了......
#include <stdio.h>
int fun0()
{
return 0;
}
int fun1()
{
return 1;
}
int fun2()
{
return 2;
}
int main(int argc, char* argv[])
{
int (*f[]) (void) = {fun0, fun1, fun2};
printf("%d\n", f[0]());
printf("%d\n", f[1]());
printf("%d\n", f[2]());
return 0;
}
我只是在上面的答案中添加一些内容。函数指针数组可以由枚举变量索引,显示每个索引的操作类型。看一下下面的例子。在这里,我们使用tyepdef作为函数指针运算符。然后我们创建一个名为act的函数指针数组。最后,我们将数组初始化为递增和递减函数。在这种情况下,索引0表示增量,索引1表示减量。我们使用具有INCR和DECR的枚举,而不是使用这个原始索引,对应于索引0,1。
#include<stdio.h>
#include<stdlib.h>
typedef void (*operate)(int *, int);
void increment(int *, int);
void decrement(int *, int);
enum {
INCR, DECR
};
int main(void){
int a = 5;
operate act[2] = {increment,decrement};
act[INCR](&a,1);
printf("%d\n",a);
act[DECR](&a,2);
printf("%d\n",a);
return 0;
}
void increment(int *a, int c){
*a += c;
}
void decrement(int *a, int c){
*a -= c;
}
这是一个显示正确语法的工作示例:
#include <stdio.h>
int test1(void) {
printf("test1\n");
return 1;
}
int test2(void) {
printf("test2\n");
return 2;
}
int main(int argc, char **argv) {
int (*fparr[2])(void) = { test1, test2 };
fparr[0]();
fparr[1]();
return 0;
}
示例代码:
static int foo(void) { return 42; }
int (*bar[5])(void) = { foo, foo, foo, foo, foo };
请注意,类型int (*)()
和int (*)(void)
是不同的类型 - 前者表示具有固定但未指定数量的参数的函数,而后者表示不带参数的函数。
另请注意,C声明符语法遵循与表达式相同的规则(特别是运算符优先级),因此从内到外读取:
bar
表示指针(bar[5]
)和函数(*bar[5]
)的数组(int (*bar[5])(void)
)。 parens (*bar[5])
是必要的,因为postfix函数调用绑定比前缀指针间接更紧密。
可以使用默认值以另一种方式初始化函数指针数组。
#include <stdio.h>
void add(int index, int a, int b){
printf("%d. %d + %d = %d\n", index, a, b, a + b);
}
void sub(int index, int a, int b){
printf("%d. %d - %d = %d\n", index, a, b, a - b);
}
int main(){
void (*func[10])(int, int, int) = {[0 ... 9] = add};
func[4] = sub;
int i;
for(i = 0; i < 10; i++)func[i](i, i + 10, i + 2);
}
0. 10 + 2 = 12
1. 11 + 3 = 14
2. 12 + 4 = 16
3. 13 + 5 = 18
4. 14 - 6 = 8
5. 15 + 7 = 22
6. 16 + 8 = 24
7. 17 + 9 = 26
8. 18 + 10 = 28
9. 19 + 11 = 30