Code snippet: What is the output?
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Code snippet:**
prime(int *m, int *n, int *o, int *p, int *q)
{
printf("\n%d %d %d %d", *m, *n, *o, *p, *q);
}
prime(int *m, int *n, int *o, int *p, int *q)
{
printf("\n%d %d %d %d", *m, *n, *o, *p, *q);
}
int run()
{
static int a[] = {0, 1, 2, 3, 4};
static int *p[] = {a + 2, a, a + 4, a + 1};
int **ptr;
ptr = p;
**++ptr;
printf("%d %d\n", *(ptr, ptr - p));
}
What is the output?
Show answer & explanation
Answer: B. 0 1
The operator precedence and pointer arithmetic work as follows: ptr initially points to p[0] (which contains a+2). The expression **++ptr increments ptr to point to p[1], then dereferences it to get a (value 0). The comma operator in printf evaluates both expressions but returns the second: ptr - p equals 1 (ptr is at p[1]). So the output is 0 1.
Step-by-step Derivation:
- Array setup: a[] = {0, 1, 2, 3, 4}, p[] = {a+2, a, a+4, a+1}
- ptr = p; (ptr points to p[0])
- **++ptr: ++ptr makes ptr point to p[1], then **ptr dereferences: *p[1] = *a = 0
- printf("%d %d\n", *(ptr, ptr - p)): comma operator evaluates (ptr, ptr - p), returns ptr - p = 1
- *(1) is invalid syntax, but the actual second %d receives ptr - p = 1
- Output: 0 1