问题描述
根据 GNU C手册,可以使用如下函数指针来调用函数:
According to the GNU C manual, functions can be called using function pointers like so:
func (j); /* (*func) (j); would be equivalent. */
所以我在这里的理由是:func
本身是func(int)
函数的指针.调用func(j)
时,您将隐式访问指针func
的值(您将移至func
所在的存储位置),其方式与使用具有整数指针的方式相同. ,然后使用*
访问存储在内存中该位置的值.这与您可以使用(*func)(j)
调用同一函数的事实是一致的.
So my reasoning here is: func
itself is a pointer to the func(int)
function. When you call func(j)
, you are implicitly accessing the value of the pointer func
(you are moving to the memory location where func
is), in the same way as when you have a pointer to an integer, for example, and you access the value stored in that position of the memory using *
. That would be consistent with the fact that you can call that same function using (*func)(j)
.
实际上,在 cprogramming.com 中,他们说您可以拥有指向函数指针的指针.因此,我因此猜测它们的工作原理与任何其他类型的指针一样.
In fact, in cprogramming.com, they say you can have a pointer to a pointer of a function. So I am therefore guessing they work like any other kind of pointers.
但是如果是这样,为什么这段代码可以正常工作?
But if that's the case, why is it that this code works?
#include <stdlib.h>
#include <stdio.h>
void a(int n) {
printf("%d\n", num);
}
int main() {
int x = 5;
void (*func)(int); // Declare a pointer to a function
func = &a; // Pointer to a pointer to a function
(*func)(x); // Calls the function (why?)
func = a; // Pointer to a function
(*func)(x); // Calls the function (makes sense)
}
此外,如果您致电:
printf("%s\n", (&a == a) ? "True" : "False");
它将打印True
!
It prints True
!
例如,我确定&foo
与&&foo
不相同,因此为什么 func
与&func
相同的原因为何 ?
I am sure that &foo
is not the same as &&foo
, for example, so why does it seem to be the case that func
is the same as &func
?
推荐答案
N1570 6.3.2.1左值,数组和函数指示符表示:
N1570 6.3.2.1 Lvalues, arrays, and function designators says:
此处a
和*func
是功能指示符,因为它们具有功能类型. &a
中的a
不会转换为指针,因为它是一元&
运算符的操作数,并且该函数的指针由&
运算符检索.另一方面,根据该规则,func = a;
中的a
被转换为指向该函数的指针.因此,此代码中的a
和&a
是等效的.
Here a
and *func
are function designators because they have function type. a
in &a
is not converted to a pointer because it is the operand of the unary &
operator and the pointer to the function is retrieved by the &
operator.On the other hand, a
in func = a;
is converted to the pointer to the function according to this rule.Therefore a
and &a
in this code are equivalent.
func(x);
中的func
也会根据此规则转换为指针.
Also func
in func(x);
is converted to the pointer according to this rule.
(*func)(x);
是:
-
func
根据此规则转换为指针 -
*func
中的 -
*func
根据此规则转换为指针
*
取消了指针的引用func
is converted to the pointer according to this rule- The pointer is dereferenced by
*
in*func
*func
is converted to the pointer according to this rule
因此(*func)(x);
等同于func(x);
.
这篇关于为什么func与C中的&func相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!