ALL 15 17 18 19 16.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
ALL 15 17 18 19 16. (C Question) Pointer arithmetic What is the output of the following code snippet? #include <stdio.h> void main() { intx = 4; int *p = &x; int *k = p++; intr=p—k; printf(“%d”, r); } Pick ONE option Clear Selection G Saved! 12/44 - A) 01 hour 12 mins - B) G
Show answer & explanation
Post-increment p++ returns the original pointer value before incrementing, so k gets the original address of x. After the assignment, p is incremented by one pointer unit (4 bytes for int). The subtraction p - k performs pointer arithmetic, yielding the difference in number of elements (1 int), not bytes.
Step-by-step Derivation:
Step 1: x = 4, p = &x (points to x)
Step 2: k = p++ means k stores the old value of p (pointing to x), then p increments to point to the next int address
Step 3: r = p - k subtracts pointers; result is the difference in array indices = 1
Step 4: printf("%d", 1) outputs: 1