What will be the output of the following C code snippet?
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What will be the output of the following C code snippet?
#include <stdio.h>
int main() {
int a[] = {1, 2, 4, 6, 8};
int* p[] = {a, a+1, a+2, a+3, a+4};
int** p1 = p;
int** p2 = (p+2);
printf("%d %d %d\n", *p2 - *p1, *(p2+1) - *p1, **p1);
return 0;
}
Show answer & explanation
The key is understanding pointer-to-pointer arithmetic and array indexing. p1 points to p[0] (which holds address a), and p2 points to p[2] (which holds address a+2). The expressions *p2 - *p1 and *(p2+1) - *p1 perform pointer arithmetic (subtracting addresses), yielding element differences of 2 and 3 respectively. **p1 dereferences to get the value at a[0], which is 1.
Step-by-step Derivation:
Step-by-step execution:
Array
a[] = {1, 2, 4, 6, 8}has elements at addresses: &a[0], &a[1], &a[2], &a[3], &a[4]Array
p[] = {a, a+1, a+2, a+3, a+4}stores pointers:- p[0] = a (points to &a[0])
- p[1] = a+1 (points to &a[1])
- p[2] = a+2 (points to &a[2])
- p[3] = a+3 (points to &a[3])
- p[4] = a+4 (points to &a[4])
p1 = p→ p1 points to p[0]p2 = p+2→ p2 points to p[2]Evaluate printf arguments:
*p2= p[2] = a+2 (pointer to &a[2])*p1= p[0] = a (pointer to &a[0])*p2 - *p1= (a+2) - a = 2 (pointer subtraction yields element count)*(p2+1)= p[3] = a+3 (pointer to &a[3])*(p2+1) - *p1= (a+3) - a = 3**p1= *(p[0]) = *a = a[0] = 1
Output:
2 3 1