Which of the following statements is correct?
sir, but why can't we take this example here ... I know it is not mentioned here explicitly but we know that struct object may contain more than one variable, so I thought it may not be possible always ..
S1: A struct object will always occupy more space than a union object having the same elements.
Struct str { int a; char b; }
Size = size of int a + size of char b. = 4 + 1 = 5.
Union U { int a; char b; }
size = max (size of int a , sizeof char b).= size of int a = 4.
I meant second statement of question Given an int array Arr and a struct object Str both having same size in memory, Arr[100] and Str[100] always have the same size in memory.
Given an int array Arr and a struct object Str both having same size in memory, Arr[100] and Str[100] always have the same size in memory.
if both objects have the same size of memory then 100 objects of both will also have the same memory.
" Given an int array Arr " refers to one element of an array and not the entire array . That is ambiguous.
Something is not right.
This question is supposed to involve many concepts.
Now, coming to S1, it is FALSE. Both struct and union will be having same size for a single object. Only with multiple objects, struct will have more size.
For S2, it is true. Because an array - be of any object- will just multiply the memory requirement of a single object. This statement is not asking for structure padding, which happens inside a single structure object. Here arr is an array and hence arr[100] is an array of arrays.
In structure padding, size of a single struct object is increased by adding padding bits to ensure proper alignment with the architecture causing an increase in size compared to the sum of sizes of the individual components.
Size of a struct = Sum of the sizes of all constituent members.
Size of a union = Size of the largest member.
If struct and union have the one, same member, then size of struct = size of union.
S1 is false.
If size of the struct Str = x, and size of array Arr = x; then size of Str[[100] = 100x, and size of Arr[100] = 100x.
S2 is true.
Option B