I wrote some code to know how function pointer works. I run the following C++ code on some IDEs, the results are the same.
#include "stdafx.h"
int *function(){
static int a=1;
return &a;
}
typedef struct{
int *(*pt_1)();
int *(*pt_2)();
}x_t;
int _tmain(int argc, _TCHAR* argv[])
{
x_t s;
s.pt_1 = function;
s.pt_2 = &function;
printf("%x\n",s.pt_1); //Result: 0x013011a9
printf("%x\n",*s.pt_1); //Result: 0x013011a9
printf("%x\n",**s.pt_1); //Result: 0x013011a9
printf("%x\n",s.pt_1()); //Result: 0x01307000
printf("%x\n",*s.pt_1()); //Result: 1
printf("%x\n",s.pt_2); //Result: 0x013011a9
printf("%x\n",*s.pt_2); //Result: 0x013011a9
printf("%x\n",**s.pt_2); //Result: 0x013011a9
printf("%x\n",s.pt_2()); //Result: 0x01307000
printf("%x\n",*s.pt_2()); //Result: 1
return 0;
}
My questions:
s.pt_1 == s.pt_2 == *s.pt_1 = **s.pt_1
?s.pt_1()
point to ? Where does it locate on memory?Similar to using the name of an array, using the name of a function will make it decay into a pointer at the slightest provocation.
s.pt_1 = function;
Here function
decays into a pointer to the function.
s.pt_2 = &function;
Here you actually take the address of the function, which results in the same pointer as in the first case.
printf("%x\n",s.pt_1); //Result: 0x013011a9
printf("%x\n",*s.pt_1); //Result: 0x013011a9
printf("%x\n",**s.pt_1); //Result: 0x013011a9
On the first line pt_1
is a pointer to a function, and the address stored in the pointer is displayed.
On the second line, you dereference the pointer and gets access to the function itself. Which the decays into a pointer when passed to a function.
On the third line, you dereference the pointer to get the function, which then decays to a pointer when you use it with another *
. The second star results in a value that again decays into a pointer when passed to a function. Etc.
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