Interview Questions
Pointers · Study material
C Pointers Interview Questions and Answers
1. What is a pointer?
A variable that stores the memory address of another variable. Its type tells the compiler what kind of value is at that address and how far p + 1 moves.
2. What is the difference between *p++, (*p)++ and ++*p?
*p++ reads the value, then moves the pointer to the next element. (*p)++ increments the value p points to and leaves p alone. ++*p also increments the value, but the expression gives the new value.
3. What is a NULL pointer, and why use it?
A pointer that points to no object. It marks "no address yet" or "not found" and can be tested before dereferencing. Dereferencing NULL is undefined behaviour.
4. What are wild and dangling pointers?
A wild pointer was never initialised. A dangling pointer points to memory that was freed or to a local variable whose function has returned. Both lead to undefined behaviour.
5. What is a void pointer?
A generic pointer (void *) that can hold any object address. It cannot be dereferenced or used in arithmetic until it is converted to a typed pointer.
6. Is an array name a pointer?
No. It decays to a pointer to its first element in most expressions, but it is not a variable: you cannot assign to it, and sizeof and & treat it as the whole array.
7. How is call by reference done in C?
C passes everything by value, so you pass the address of a variable and the function changes it through the pointer, as in swap(&a, &b).
8. What is the difference between const int *p and int *const p?
The first is a pointer to a constant int: you cannot change *p, but you can point p elsewhere. The second is a constant pointer: you can change *p, but not p itself.
9. What is a function pointer? Give a use.
A pointer that stores the address of a function, declared like int (*f)(int, int). It is used for callbacks, menus and the comparator of qsort().
10. What is a memory leak?
Memory allocated with malloc() that is never freed, usually because the last pointer to it was overwritten or went out of scope.
11. Why does a function need a pointer to a pointer to change a pointer?
Because the pointer argument is a copy. To make the caller's pointer point somewhere new – for example the head of a linked list – the function needs its address, a T **.
12. Can two pointers be added?
No. You can add an integer to a pointer, subtract two pointers into the same array (the result is a ptrdiff_t element count) and compare them, but adding two addresses has no meaning.