For function pointer "fptr",why is value of "fptr" and *fptr same?What *fptr even mean?I only knew (*fptr)() or fptr()
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.
Thokchom
Bear with me, I am a slow learner, but I am sincere and really interested to learn programming.
Updated on June 28, 2022Comments
-
Thokchom almost 2 years
Why is a
function pointer
behaving like anarray pointer
as far as this behavior goes?I mean, let's begin with the case of an arraylist[]
where we'll consider&list
andlist
.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 doesfptr
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 asfptr()
,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