Difficulty: Hard
Correct Answer: 2, Garbage value
Explanation:
Introduction / Context:
This question tests your understanding of pointer casts between char
and int*
, byte-level access, alignment, and the consequences of reading an int
from a non–int
-aligned address. Many platforms allow the code to compile but may yield implementation-defined or undefined results at runtime when misaligned.
Given Data / Assumptions:
char*
pointing to the first byte of arr.int
is 2.int*
from p + 1
, which is typically misaligned.
Concept / Approach:
p reads the very first byte of the array’s memory, which for the integer 2 on little-endian is 0x02 → prints 2. Then p = (int)(p + 1) creates an int*
at the following byte boundary. Dereferencing *p reads four bytes starting at a nonaligned address, yielding a “garbage” integer (and possibly a bus error on strict-alignment systems).
Step-by-Step Solution:
Initial: p points to arr as bytes.Print p → 2.Advance by 1 byte and cast to int → potential misalignment.Print *p → implementation-defined “garbage” value.
Verification / Alternative check:
On a platform that traps misaligned access, the program may fault. On tolerant CPUs, the value varies by endianness and representation.
Why Other Options Are Wrong:
(a) assumes a clean aligned int
read. (b) suggests a forced zero which is unlikely. (d) prints zeros without basis.
Common Pitfalls:
Forgetting alignment rules; assuming bytes map to integers uniformly across architectures.
Final Answer:
2, Garbage value
Discussion & Comments