What is printed by this C code: int a; int *p = &a, *q = &a; printf(“%td”, q – p);?
Correct answer C. 5
Explanation
Subtracting two pointers into the same array gives the number of elements between them, not the number of bytes, and the result has type ptrdiff_t (printed with %td). a[6] and a[1] are 5 elements apart. Answer 20 is the byte distance with 4-byte ints. Subtracting pointers that do not point into the same array object is undefined behaviour.
Answer checked How we write and check questions
Discussion