如何理解int *(*a[5])(int, char*);

  • Post author:
  • Post category:其他



int *(*a[5])(int, char*);




拆开来分析:




typedef int* (*f)(int,char*);




f a[5];



所以a是个5个元素的数组,每个元素为函数指针.




可用代码验证:

#include <stdio.h>
#include <stdlib.h>

int* (*a[5])(int,char*);

int *foo(int n, char *s)
{
	int *p;

	p = (int *)malloc(sizeof(int));
	*p = n + atoi(s);

	return p;
}

int main(int argc, char *argv[])
{
	int *p;

	a[0] = &foo;
	p = (*a[0])(1, "2");

	printf("%d\n", *p);

	return 0;
}

输出:

3

顺便把函数指针再复习一下:

#include <stdio.h>
#include <stdlib.h>

//int* (*a[5])(int,char*);

typedef int (*f)(int,char*);
f funp;

int foo(int n, char *s)
{
	return 10086;
}

int main(int argc, char *argv[])
{
	funp = &foo;

	printf("%x\n",funp);
	printf("%d\n",(*funp)(6,"test"));

	return 0;
}

输出:

3f1000

10086