Search code examples
cprintffunction-pointersmemory-address

Why does printf changes the address of a function pointer?


Adressing operator inside the printf changes the address of the function pointer from a regular adress to 0x1000. Why this happens and what does it mean ?

#include <stdio.h>
int main()
{
    int (*fp) (int);
    printf("%p\n", (fp));
    printf("%p", (fp));
}

When I run this I get 0x560cb44ce060 0x560cb44ce060 as expected but when ı run this

#include <stdio.h>
int main()
{
    int (*fp) (int);
    printf("%p\n", (fp));
    printf("%p", &(fp));
}

ı get 0x1000 0x7ffcc92c8990 I really can not figured out what does change when I add & operator at the last line.


Solution

  • In the first case of using printf there is outputted the uninitialized pointer fp (its garbage value)

    int (*fp) (int);
    printf("%p\n", (fp));`
    

    In the second case of using printf there is outputted the valid address of the pointer fp itself

    printf("%p", &(fp)); 
    

    So there is nothing changed. There are outputted two different entities: the value stored in a variable (pointer) and the address of the variable itself.

    Pay attention to that the conversion specifier p expects a pointer of the type void * but function pointers may not be converted to the type void *.