就此行为而言,为什么 函数指针
表现得像 数组指针
?我的意思是,让我们从数组 list[ ]
我们将在其中考虑 &list
和 list
。
char name[5]= "Eric",(*aptr)[5]=&name;
printf("%p,%p",*aptr,name); //BOTH ARE NUMERICALLY SAME
我们也可以将数组元素称为 (*aptr)[1]
、(*aptr)[2]
等。我明白这里发生了什么.
但为什么同样适用于函数?毕竟这样的“函数”不是与数组相似的元素的连续内存块。考虑一下。
假设fptr
是我程序中的函数指针。为什么fptr
和*fptr
在打印时给出相同的值?什么是*fptr
甚至是什么意思?我只知道我们可以使用它的指针作为 (*fptr)()
或 fptr()
来调用函数,但是 *fptr
又是什么呢?
#include<stdio.h>
void foo(){};
int main(void)
{
void (*fptr)()=foo;
printf("%p,%p",fptr,*fptr);
}
结果- 00401318 00401318
指针是指向一个内存位置。一个函数在内存中并且有一个起始地址。您可以很好地取消引用函数名称(这是一个指针)以获取该地址的函数。
来自 Stephen Prata“Cpp Primer Plus”
History Versus Logic Holy syntax!
How can pf and (*pf) be equivalent?
One school of thought maintains that because pf is a pointer to a
function, *pf is a function; hence, you should use (*pf)() as a
function call. A second school maintains that because the name of a
function is a pointer to that function, a pointer to that function
should act like the name of a function; hence you should use pf() as a
function call. C++ takes the compromise view that both forms are
correct, or at least can be allowed, even though they are logically
inconsistent with each other. Before you judge that compromise too
harshly, reflect that the ability to hold views that are not logically
self-consistent is a hallmark of the human mental process.