C Tutorial
In pointers the way we can reference variables of type int, char and float etc using addresses, c pointers can also point to the function since c function have addresses.
If we know the function address, we can point to it using pointers and also the another way to invoke that function.
func_ptr is a pointer to a function which returns an function return type
pointer to function syntax,
(*func_ptr)(arg1,...);
Writing memory resident programs.
viruses program and vaccines to remove the virsuses.
COM / DCOM components development.
Connect events to function calls(VC++).
This c program is used to get the address of show function and displayed it.
To obtain the address of a function, we need to use the name of the function.
#includevoid main() { void show(); printf("\nMain method!"); printf("\nAddress of show function: %u", show); show(); } void show() { printf("\nShow method!"); }
Output:
$ cc pointer-to-function.c $ ./a.out Main method! Address of show function: 4195674 Show method!
#includevoid main() { void show(); void (*func_ptr)(); printf("\nMain method!"); // assign address of function 'show' to function pointer func_ptr = show; printf("\nAddress of show function: %u", func_ptr); // invokes show function (*func_ptr)(); } void show() { printf("\nShow method!"); }
Output:
$ cc pointer-to-function.c $ ./a.out Main method! Address of show function: 4195674 Show method!
This c program invokes the show funation and returns integer value and also shows how to invoke the show function using pointer.
func_ptr is a pointer to invoke show function which returns an int data type.
#includevoid main() { int output; int show(); int (*func_ptr)(); printf("\nMain method!"); func_ptr = show; printf("\nAddress of show function: %u", func_ptr); // invokes show function output = (*func_ptr)(); printf("\nReturn value from show function: %d", output); } int show() { printf("\nShow method!"); return 10; }
Output:
$ cc pointer-to-function.c $ ./a.out Main method! Address of show function: 4195712 Show method! Return value from show function: 10
This c program invokes the show funation with int argument and returns integer value and also shows how to invoke the show function using pointer.
func_ptr is a pointer to invoke show function with integer argument which returns an int data type.
#includevoid main() { int output; int show(int); int (*func_ptr)(int); printf("\nMain method!"); func_ptr = show; printf("\nAddress of show function: %u", func_ptr); // invokes show function output = (*func_ptr)(20); printf("\nReturn value from show function: %d", output); } int show(int val) { printf("\nShow method!"); return val; }
Output:
$ cc pointer-to-function.c $ ./a.out Main method! Address of show function: 4195712 Show method! Return value from show function: 20
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page