加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是否可以在C中增加函数指针

发布时间:2020-12-16 10:10:24 所属栏目:百科 来源:网络整理
导读:我有以下代码,我得到分段错误,因为我的函数指针指向一个函数指针数组,并且在函数指针的增量未指向函数指针数组中的下一个元素之后. int f2(int);int f1(int);int(*fp[2])(int) = {f1,f2};int f1(int x){return (x+10);}int f2(int y){return (y+20);}int mai
我有以下代码,我得到分段错误,因为我的函数指针指向一个函数指针数组,并且在函数指针的增量未指向函数指针数组中的下一个元素之后.

int f2(int);
int f1(int);
int(*fp[2])(int) = {f1,f2};

int f1(int x)
{
return (x+10);
}


int f2(int y)
{
return (y+20);
}

int main() {
    int sum = 0;
    int (*fp1) (int);

    fp1 = fp;
    printf("addr of fp1 is %xn",fp1);
    ++(fp1);
    printf("after increment addr of fp1 is %xn",fp1);
    sum = (*fp1)(sum);
        printf("%d n",sum);
        return 0;
    }

但是,当我使用指向函数指针的指针时,如:

int(** fp1)(int);
然后代码工作正常.
请告诉:

1-为什么只是函数指针不起作用.

2指向函数的指针,即fp1仅在执行fp1时将地址递增1.

3-当我通过fp1 = fp [0];那么它也不能同时使用指向函数的指针…以及指向函数的指针. fp和fp [0]指向不同的地址吗?

解决方法

指向功能的指针

递增和递减运算符对于指向函数的指针无效.

以下是C标准草案(N3337)的相关文字:

5.3.2 Increment and decrement

1 The operand of prefix ++ is modified by adding 1,or set to true if it is bool (this use is deprecated). The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a completely-defined object type. The value is the new value of the operand; it is an lvalue. If x is not of type bool,the expression ++x is equivalent to x+=1.

指向函数的指针的类型既不是算术类型,也不是指向完全定义的对象类型的指针.因此,不能应用于指向函数的指针.

就C而言,C99标准(n1256)说:

6.5.3.1 Prefix increment and decrement operators

1 The operand of the prefix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.

2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1). See the discussions of additive operators and compound assignment for information on constraints,types,side effects,and conversions and the effects of operations on pointers.

6.5.6 Additive operators

2 For addition,either both operands shall have arithmetic type,or one operand shall be a pointer to an object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

同样,由于相同的原因,指向函数的指针不能递增.

指向函数的指针数组/指向函数指针的指针

这条线

int(*fp[2])(int) = {f1,f2};

声明一个指向函数的指针数组.因此,表达式fp [0]和fp [1]是有效表达式.您可以指向指向函数对象的指针,该指针与increment运算符一起使用.

int (**fpp)(int) = fp;
(*fpp)(10);  // Calls f1(10)
fpp[0](10);  // Calls f1(10)
fpp[1](10);  // Calls f2(10)
++fpp;
(*fpp)(20);  // Calls f2(20)
fpp[0](20);  // Calls f2(20)

不幸的是,gcc 4.7.3允许编译以下语句,而g则不允许.

int(*fp[2])(int) = {f1,f2};
int (*fpp)(int) = fp;

调用

fpp(10);

在这种情况下导致未定义的行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读