函数指针 - 自动取消引用
可能的重复:
函数指针的取消引用是如何发生的?
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”被打印四次。通过应用函数指针,它是否隐式解除引用?基本上我想知道函数指针实际上是如何存储的,因为上面的内容有点令人困惑。
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);
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这只是 C 的一个怪癖。没有其他原因,但 C 标准只是说取消引用或获取函数的地址只会计算出指向该函数的指针,而取消引用函数指针只会计算回函数指针。
这种行为(因此显然)与一元
&
和*
运算符对普通变量的工作方式非常不同。因此,
所有的操作都完全相同,为您提供一个指向
myprint
的函数指针,类似地,
执行相同的操作,调用存储在
test2
中的函数指针。因为 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.So,
All just do exactly the same, gives you a function pointer to
myprint
Similarly,
Does the same, call the function pointer stored in
test2
. Because C says it does.