Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to function pointer in C++

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:

    1. Why s.pt_1 == s.pt_2 == *s.pt_1 = **s.pt_1 ?
    1. Where address does the s.pt_1() point to ? Where does it locate on memory?
like image 860
Ngo Thanh Nhan Avatar asked Jan 24 '16 09:01

Ngo Thanh Nhan


1 Answers

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.

like image 144
Bo Persson Avatar answered Nov 01 '22 16:11

Bo Persson