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 %x\n",fp1); ++(fp1); printf("after increment addr of fp1 is %x\n",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 adding1
,or set totrue
if it isbool
(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. Ifx
is not of typebool
,the Expression++x
is equivalent tox+=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);
在这种情况下导致未定义的行为.
总结以上是内存溢出为你收集整理的是否可以在C中增加函数指针全部内容,希望文章能够帮你解决是否可以在C中增加函数指针所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)