edited by
20,536 views
51 votes
51 votes

Consider the following C declaration:

struct {
    short x[5];  
    union { 
        float y; 
        long z; 
    } u;
 )t;

Assume that the objects of the type short, float and long occupy $2$ bytes, $4$ bytes and $8$ bytes, respectively. The memory requirement for variable $t$, ignoring alignment consideration, is:

  1. $22$ bytes
  2. $14$ bytes
  3. $18$ bytes
  4. $10$ bytes
edited by

4 Answers

Best answer
62 votes
62 votes

Correct Option: C

Here, structure creates the memory for '$\text{array and union}$', but union only creates the memory for only '$\text{long z}$' which is the largest size data type inside it.

Hence,

$short \times [5] = 5*2 = 10$ bytes  [ shorts take $2$ bytes]

$\text{long z}  = 8$ bytes

So, ($10+8) = 18$ bytes

edited by
29 votes
29 votes

When memory would be assigned for the array 

short x[5];

Memory requirement = $5*2B=10B$

 

And for

union {
float y;
long z;
}

Memory requirement = $8B$ because the size of a union is the size of it's largest data member.

Hence, total memory requirements = $18B$

Option C



Let's consider memory alignment now.

If machine architecture has word size = 32 bits, then every piece of addressable memory must be in multiples of a word. Or equivalently 32 bits. Or, equivalently 4B.

Hence for:

short x[5];

Memory requirement = $5*2B=10B$ $+2B$ of padding = $12B$ (Multiple of 4B)

for:

union {

Memory requirement = $8B$

So, total = $20B$


If machine architecture has word size = 64 bits, then every piece of addressable memory must be in multiples of a word. Or equivalently 64 bits. Or, equivalently 8B.

Hence for:

short x[5];

Memory requirement = $5*2B=10B$ $+6B$ of padding = $16B$ (Multiple of 8B)

for:

union {

Memory requirement = $8B$

So, total = $24B$

2 votes
2 votes
struct ( 
    short x[5];  
    union { 
        float y; 
        long z; 
    } u;
 )t;

union considers max value only.

struct (

short x[5];

8bytes; //long

)t;

struct considers every value

5*2// 5 values of short =8 =>18

0 votes
0 votes
Short[5]=5*2=10

Max[float,long]= max[4,8]=8

Total=short[5]+max[4,8]=10+8=18
Answer:

Related questions

41 votes
41 votes
7 answers
1
Kathleen asked Sep 14, 2014
36,411 views
The number of tokens in the following C statement isprintf("i=%d, &i=%x", i, &i);$3$$26$$10$$21$
52 votes
52 votes
3 answers
3
Kathleen asked Sep 14, 2014
11,745 views
The most appropriate matching for the following pairs$$\begin{array}{|ll|ll|}\hline X: & \text{m = malloc(5); m = NULL;} & 1: & \text{using dangling pointers} \\\hline Y...