Is it possible to access the address of a C function?

Asked

Viewed 401 times

2

It is possible to access the address, literally, of some function and C and also store in some variable of the main(), etc..?

int f1()
{

}; 

int main()
{ 
    int *ponteiro; 
    ponteiro = &f1; 
    printf("%d\n", ponteiro); return 0; 
}
  • You have the example of the code?

  • No, but suppose: int F1(){}; int main(){ int *pointer; pointer = &F1; printf("%d n", pointer); Return 0; I wonder if that’s possible.

  • This may help you: https://answall.com/questions/2983/como-passar-uma-fun%C3%A7%C3%A3o-como-par%C3%A2metro-em-c

1 answer

5


Every function is an implicit pointer, so your name is already your address, just print your content as a pointer (%p) which is the address.

Unlike people who imagine these names all called identifiers or symbols are not loose things, this is a common design pattern that determines that these names are simple and readable ways to access a memory address, so we can say that they are always variables (although technically some of them are immutable). The name of a function is nothing more than an immutable variable that stores the memory address where the code of this function is.

You don’t have to make all this mess:

#include <stdio.h>

int f1() {}

int main(void) {
    printf("%p, %p, %p, %p", main, printf, scanf, f1);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

When you use parentheses, with or without arguments, in this name is saying to the compiler who wants to call the function and he puts an instruction to call in the executable, but if you do not use parentheses this name is used as a value like any other and can be a pointer, in case for a code of a function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.