© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

5.  When would you use a pointer to a function?

Ans:
Pointers to functions are interesting when you pass them to other functions. A function that takes function pointers says, in effect, Part of what I do can be customized. Give me a pointer to a function, and I’ll call it when that part of the job needs to be done. That function can do its part for me. This is known as a callback. It’s used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application.

As a simpler example, say you have an array of character pointers (char*s), and you want to sort it by the value of the strings the character pointers point to. The standard qsort() function uses function pointers to perform that task. qsort() takes four arguments,
- a pointer to the beginning of the array,
- the number of elements in the array,
- the size of each array element, and
- a comparison function, and returns an int.

Ex - 1:  Predict the output or error(s) for the following:
 main()
{
char *p;
p="%d\n";
           p++;
           p++;
           printf(p-2,300);
}

Ans:
300

Explanation:

The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed.

Ex - 2: what is the output?:

void main()
{
            void *v;
            int integer=2;
            int *i=&integer;
            v=i;
            printf("%d",(int*)*v);
}

Ans:
Compiler Error. We cannot apply indirection on type void*.

Explanation:

Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for,
1.      Passing generic pointers to functions and returning such pointers.
2.      As a intermediate pointer type.
3.      Used when the exact pointer type will be known at a later point of time.


SLogix Student Projects
bottom