Sunday, November 1, 2009

C Skills : tutor 6 : Function Pointers - Part1

Function Pointers are pointers, i.e. variables, which point to the address of a function. You must keep in mind,that a running program gets a certain space in the main-memory. Both, the executable compiled program code and the used variables, are put inside this memory. Thus a function in the program code is, like e.g. a character field, nothing else than an address. It is only important how you, or better your compiler/processor interpret

the memory a pointer points to.

What is “Pointer to function”?Answer : Actually Pointer to Function and Function Pointer are same.


Step1:Declare/Define a Function Pointer

Since a function pointer is nothing else than a pointer variable, it must be defined as usual. In the following example we define two function pointers named pt2Function. They point to functions,
which take one float and two char and return an int.
define a function pointer and initialize to NULL

int (*pt2Function)(float, char, char) = NULL;

We may or may not assign NULL, However Its better.

Step2:Assign an Address to a Function Pointer

It’s quite easy to assign the address of a function to a function pointer. You simply take the name of a suitable and known function or member function. Although it’s optional for most compilers you should use the address operator & infront of the function’s name in order to write portable code.


int funtion1(float a, char b, char c)

{

printf("function1\n");

return (2a+2b+3c) ;

}

pt2Function = function1;


No comments:

Post a Comment