Pointer to a function pointer in C ++

I wrote code to find out how a function pointer works. I am running 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 ?
    1. Specify the address pointed to by s.pt_1() ? Where is he in memory?
+7
c ++ memory function-pointers
source share
2 answers

Like using an array name, using a function name will cause it to break into a pointer at the slightest provocation.

 s.pt_1 = function; 

Here function decays to a pointer to a function.

 s.pt_2 = &function; 

Here you actually take the address of the function, which leads to 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 

The first line of pt_1 indicates the function pointer, and the address stored in the pointer is displayed.

In the second line, you look for a pointer and get access to the function itself. Which breaks into a pointer when passing a function.

On the third line, you search for a pointer to get a function that then decays to a pointer when you use it with another * . The second star results in a value that goes back to the pointer when the function is passed. Etc.

+4
source share

The problem is that you basically cannot do anything with a “functional object” ... C ++ only manages “function pointers”.

Therefore, the function will implicitly decay into a pointer to a function for any use ... no matter how many * you put in front of it.

Something similar happens with arrays, where they implicitly decay to a pointer to the first element, with the difference that you can perform some operation on arrays (for example, sizeof ), even if it is forbidden using functions.

Given that in C ++ there is no (portable) way to create new functions at runtime, the restriction on the impossibility of managing function objects does not really matter. In any case, you can only deal with pointers to existing functions ...

+1
source share

All Articles