In C, mixing char* and int* and unaligned reads: what prints?
#include
int main()
{
int arr[3] = {2, 3, 4};
char p;
p = (char)arr;
p = (char*)((int*)(p));
printf("%d, ", p);
p = (int)(p + 1);
printf("%d", p);
return 0;
}
-
A2, 3
-
B2, 0
-
C2, Garbage value
-
D0, 0
-
EUndefined behavior: may trap
Answer
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:
- arr = {2, 3, 4}
- p is a
char*pointing to the first byte of arr. - Ordinary little-endian assumptions explain why the first byte of the first
intis 2. - The code later forms an
int*fromp + 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