Sub topic 18
Strategies for GATE-Style C Questions
Assume you know basic C syntax, binary and hexadecimal notation, functions, arrays, and compilation. This chapter gives a systematic method for pointer, memory, and recursion questions. The goal is to reason from the C rules instead of guessing from familiar-looking output.
A reliable solving method
Read the code in this order:
- Identify the type of every important expression.
- Mark each variable's current value and address.
- Apply operators according to precedence.
- Check whether an operation is defined by the C standard.
- Trace calls, returns, and side effects.
- Only then calculate the output or complexity.
For pointers, record both the pointer value and the object it points to. For arrays, remember that an array expression usually converts to a pointer to its first element, but sizeof is an important exception.
| Pattern | Main question |
|---|---|
| `*p++` | Is the old pointed-to value read before `p` advances? |
| `(*p)++` | Is the pointed-to object incremented? |
| `a[i]` | Is this equivalent to `*(a + i)`? |
| `sizeof a` | Is `a` an actual array or a pointer parameter? |
| Recursive call | What is the base case and how many calls are created? |
Separate defined behavior from traps
A result is not a valid answer if the program has undefined behavior. Common causes include:
- Dereferencing
NULLor an uninitialized pointer. - Accessing an array outside its bounds.
- Using memory after
free. - Modifying a scalar more than once between sequence points in an unsafe expression.
- Reading an uninitialized automatic variable.
- Subtracting pointers that do not point into the same array.
#include <stdio.h>
int main(void) {
int a[3] = {10, 20, 30};
int *p = a;
printf("%d %d\n", *p++, (*p)++);
printf("%d %d\n", a[0], a[1]);
return 0;
}The first operand reads a[0] and advances p. The second operand increments a[1]. However, in a question where several arguments modify the same object without a guaranteed evaluation order, do not assume a particular order. Classify the expression as undefined or unspecified when the standard requires that conclusion.
Trace recursion mathematically
For recursion, write the base case first. Then count recursive calls rather than only counting printed lines.
If a function makes two calls on inputs near n - 1, its recurrence may be:
T(n) = 2T(n - 1) + Θ(1)
This gives Θ(2^n) time. If each call makes one call on n - 1, the time is usually Θ(n), and the maximum stack depth is also Θ(n).
Exercise
What is the first thing to check after finding the apparent output of a pointer question?
Show answer
Check whether every access, pointer operation, and modification has defined behavior under the C standard.