A Place for Latest Exam wise Questions, Videos, Previous Year Papers, Study Stuff for MCA Examinations - NIMCET
Previous Year Question (PYQs)
3
Suppose you are compiling on a machine with $1$-byte chars, $2$-byte shorts, $4$-byte ints, and $8$-byte doubles, and with alignment rules that require the address of every primitive data element to be an integer multiple of the element's size. Suppose further that the compiler is not permitted to reorder fields; padding is used to ensure alignment. How much space will be consumed by the following array?
struct { short s; char c; short t; char d; double r; int i; } A[10];
Solution
$short\ s$: starts at offset $0$, size $2$, next offset $2$
$char\ c$: starts at offset $2$, size $1$, next offset $3$
$short\ t$: needs multiple of $2$, so $1$ byte padding, starts at offset $4$, next offset $6$
$char\ d$: starts at offset $6$, size $1$, next offset $7$
$double\ r$: needs multiple of $8$, so $1$ byte padding, starts at offset $8$, next offset $16$
$int\ i$: needs multiple of $4$, starts at offset $16$, next offset $20$
Struct size must be multiple of maximum alignment $8$.
So, $20$ is padded to $24$ bytes.
For $A[10]$:
$10\times24=240$ bytes
Online Test Series, Information About Examination, Syllabus, Notification and More.