Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining to which function a pointer is pointing in C?

I have a pointer to function, assume any signature. And I have 5 different functions with same signature.

At run time one of them gets assigned to the pointer, and that function is called.

Without inserting any print statement in those functions, how can I come to know the name of function which the pointer currently points to?

like image 882
Sumit Avatar asked Oct 19 '15 13:10

Sumit


People also ask

Which of the following is a pointer pointing to function?

Syntax of function pointer In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an integer value as an argument.

Can a pointer point to a function in C?

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.

How do I find the address of a function pointer?

Address of a function in C or C++ We all know that code of every function resides in memory and so every function has an address like all others variables in the program. We can get the address of a function by just writing the function's name without parentheses. Please refer function pointer in C for details.

Where are function pointers stored in memory?

That depends on your compiler and target environment, but most likely it points to ROM—executable code is almost always placed in read-only memory when available.


1 Answers

You will have to check which of your 5 functions your pointer points to:

if (func_ptr == my_function1) {     puts("func_ptr points to my_function1"); } else if (func_ptr == my_function2) {     puts("func_ptr points to my_function2"); } else if (func_ptr == my_function3) {     puts("func_ptr points to my_function3"); } ...  

If this is a common pattern you need, then use a table of structs instead of a function pointer:

typedef void (*my_func)(int);  struct Function {     my_func func;     const char *func_name; };  #define FUNC_ENTRY(function) {function, #function}  const Function func_table[] = {     FUNC_ENTRY(function1),     FUNC_ENTRY(function2),     FUNC_ENTRY(function3),     FUNC_ENTRY(function4),     FUNC_ENTRY(function5) }  struct Function *func = &func_table[3]; //instead of func_ptr = function4;  printf("Calling function %s\n", func->func_name); func ->func(44); //instead of func_ptr(44); 
like image 139
nos Avatar answered Sep 27 '22 20:09

nos