功能指针-自动解引用 [英] Function Pointer - Automatic Dereferencing

查看:68
本文介绍了功能指针-自动解引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
函数指针的解除引用如何发生?

Possible Duplicate:
How does dereferencing of a function pointer happen?

  void myprint(char* x) {
      printf("%s\n", x); 
  }

  int main() {
     char* s = "hello";
     void (*test)(char*);
     void (*test2)(char*);

     test = myprint;
     test2 = &myprint;

     test(s);
     (*test)(s);
     test2(s);
     (*test2)(s);

  }

有人可以向我解释一下以上所有代码为何有效吗? "hello"被打印四次.通过应用函数指针,是否隐式取消了引用?基本上,我想知道函数指针的实际存储方式,因为上述内容有点令人困惑.

Can anyone explain to me why all of the above code is valid? "hello" is printed four times. By applying the function pointer, is it implicitly derefenced? Basically I want to know how function pointers are actually stored, because the above is kind of confusing.

推荐答案

这只是C的一个怪癖.没有其他原因,但是C标准只是说解引用或获取函数的地址只是求一个指向的指针.该函数,然后取消引用函数指针,就可以求回到函数指针.

This is just a quirk of C. There's no other reason but the C standard just says that dereferencing or taking the address of a function just evaluates to a pointer to that function, and dereferencing a function pointer just evaluates back to the function pointer.

(显然),此行为与一元&*运算符对普通变量的工作方式非常不同.

This behavior is (thus obviously) very different from how the unary & and * operators works for normal variables.

所以

test2 = myprint;
test2 = &myprint;
test2 = *myprint;
test2 = **********myprint;

所有操作都完全相同,为您提供了一个指向myprint

All just do exactly the same, gives you a function pointer to myprint

类似地,

test2(s);
(*test2)(s);
(***********test2)(s);

相同,调用存储在test2中的函数指针.因为C会说.

Does the same, call the function pointer stored in test2. Because C says it does.

这篇关于功能指针-自动解引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆