Why is a function pointer
behaving like an array pointer
as far as this behavior goes?I mean, let's begin with the case of an array list[]
where we'll consider &list
and list
.
char name[5]= "Eric",(*aptr)[5]=&name;
printf("%p,%p",*aptr,name); //BOTH ARE NUMERICALLY SAME
and we can refer to array elements also as (*aptr)[1]
,(*aptr)[2]
, etc.I understand what's going on here.
But why is the same working for functions?After all a "function" as such is not a contiguous memory block of similar elements as an array is.Consider this.
Suppose fptr
is a function pointer as in my program.Why does fptr
and *fptr
give the same value when printed?What does *fptr
even mean?I only knew that we can invoke a function using its pointer as (*fptr)()
or as fptr()
,but what is *fptr
alone then?
#include<stdio.h>
void foo(){};
int main(void)
{
void (*fptr)()=foo;
printf("%p,%p",fptr,*fptr);
}
Result- 00401318 00401318
A pointer is to point to a memory location. A function is in memory and has a starting address. You can very well dereference the function name(which is a pointer) to obtain the function at that address.
From, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With