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:
- Why
s.pt_1 == s.pt_2 == *s.pt_1 = **s.pt_1
?
- Why
- Where address does the
s.pt_1()
point to ? Where does it locate on memory?
- Where address does the