Problem 4 [4pt] Consider the following C declaration: struct Si (char a; int b;
ID: 3596861 • Letter: P
Question
Problem 4 [4pt] Consider the following C declaration: struct Si (char a; int b; ) struct S2 (float a; double b; union U struct Si sl; struct S2 s2; Assume the machine has 1-byte characters, 4-byte integers, 8-byte floating numbers, and 16-byte double- precision floating numbers. Assume the compiler does not reorder the fields, and it leaves no holes in the memory layout. How many bytes does u occupy? If the memory address of u starts from 1000, what are the start addresses of u·s1.b and u . s2.b?Explanation / Answer
size of struct S1 is = 1(char) + 4(int) = 5 (add 3 bytes for padding) = 8 bytes;
size of struct S2 is = 8 (float) + 16(double ) = 24 bytes (here no padding is required)
/* i'll explain padding at the last */
so the union size is the greater of two so size of union is 24 bytes . As the base address is 1000 the union is occupied upto 1024 bytes.
In union you can only access one variable at a time.
While accessing s1 only 8 bytes are used so
s1.a base address is : 1000
s1.b base address is : 1004
while accessing s2 all the 24 bytes are used so
s2.a base address is : 1000
s2.b base address is : 1008
Padding :
padding is that the compiler makes the size of struct and unions to be multiples 4 so for struct S1 it is made 8 by adding 3 bytes.
/* hope this helps */
/* if any queries please comment */
/* thank you */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.