[嵌入式开发]函数指针数组详细讲解

/* definition of foo_1, foo_2, foo_3 all return void and take no args */
void (* foo[3]) ();
foo[0] = foo_1 ;
foo[1] = foo_2 ;
foo[2] = foo_3 ;

I get a compile time error, but if initialized like :

/* definition of foo_1, foo_2, foo_3 all return void and take no args */
void (* foo[3]) () = {foo_1 , foo_2, foo_3 };

There is no error, why?
=================================================讲解如下:

In the second, the initialization is part of the definition.

In the first, the initialization is separate from the definition. The
definition is complete before any of the assignment statements are
processed. The initialization statements are not part of any
definition or declaration. But definitions and declarations are the
only things allowed outside of a function. Consequently, the
initialization statements are not placed properly and a diagnostic is
required.
=====================================================================

关于函数指针数组的定义方法,有两种:一种是标准的方法;一种是蒙骗法。

第一种,标准方法:

{
分析:函数指针数组是一个其元素是函数指针的数组。那么也就是说,此数据结构是是一个数组,且其元素是一个指向函数入口地址的指针。
根据分析:首先说明是一个数组:数组名[]
其次,要说明其元素的数据类型指针:*数组名[].
再次,要明确这每一个数组元素是指向函数入口地址的指针:函数返回值类型 (*数组名[])().请注意,这里为什么要把“*数组名[]”用括号扩起来呢?因为圆括号和数组说明符的优先级是等同的,如果不用圆括号把指针数组说明表达式扩起来,根据圆括号和方括号的结合方向,那么 *数组名[]() 说明的是什么呢?是元素返回值类型为指针的函数数组。有这样的函数数祖吗?不知道。所以必须括起来,以保证数组的每一个元素是指针。

}

第二种,蒙骗法:

尽管函数不是变量,但它在内存中仍有其物理地址,该地址能够赋给指针变量。获取函数方法是:用不带有括号和参数的函数名得到。
函数名相当于一个指向其函数入口指针常量。 那么既然函数名是一个指针常量,那么就可以对其进行一些相应的处理,如强制类型转换。
那么我们就可以把这个地址放在一个整形指针数组中,然后作为函数指针调用即可。

 

Initialize the function pointer array

ContractedBlock.gif ExpandedBlockStart.gif 
 
   
#include < stdio.h >

int sum( int a, int b);
int subtract( int a, int b);
int mul( int a, int b);
int div( int a, int b);

/* initialize the pointer array */
int ( * p[ 4 ]) ( int x, int y) = {
sum, subtract, mul, div
} ;

int main( void )
{
int result;
int i = 2 , j = 2 , op;


printf(
" 0: Add, 1: Subtract, 2: Multiply, 3: Divide\n " );
do {
printf(
" Enter number of operation: " );
scanf(
" %d " , & op);
}
while (op < 0 || op > 3 );

result
= ( * p[op]) (i, j);
printf(
" %d " , result);

return 0 ;
}

int sum( int a, int b)
{
return a + b;
}

int subtract( int a, int b)
{
return a - b;
}

int mul( int a, int b)
{
return a * b;
}

int div( int a, int b)
{
if (b)
return a / b;
else
return 0 ;
}

在网上搜索发现,有一个函数指针数组英文培训讲义。非常不错,推荐如下:

转载于:https://www.cnblogs.com/cnmaizi/archive/2011/02/01/1948715.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值