【问题标题】:Function Pointer - Automatic Dereferencing [duplicate]函数指针 - 自动取消引用
【发布时间】:2011-11-23 01:06:04
【问题描述】:

可能重复:
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);

  }

谁能向我解释为什么以上所有代码都有效? “你好”打印四次。通过应用函数指针,它是否被隐式取消引用?基本上我想知道函数指针实际上是如何存储的,因为上面有点令人困惑。

【问题讨论】:

标签: c function-pointers


【解决方案1】:

这只是 C 的一个怪癖。没有其他原因,但 C 标准只是说取消引用或获取函数的地址只会计算出指向该函数的指针,而取消引用函数指针只会计算回函数指针。

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

所以,

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

只是做的完全一样,给你一个指向myprint的函数指针

同样,

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

同样,调用存储在test2中的函数指针。因为 C 说有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    相关资源
    最近更新 更多