2,043 views
9 votes
9 votes

Which of the following statements is correct?

  • S1: A struct object will always occupy more space than an union object having the same elements.
  • S2: 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.
  1. Only S1 is correct
  2. Only S2 is correct
  3. Both S1 and S2 are correct
  4. Neither S1 nor S2 is correct

2 Answers

Best answer
17 votes
17 votes

This question is supposed to involve many concepts.

  • In C both struct and union are used for collection of objects. But the difference is, in union we are supposed to use only one of them at a time. i.e., suppose we have 2 data objects - say int and a char, then it allocates memory only for int, and uses the same for char. So, at any time, we cannot use both the items but only one.

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.

edited by
0 votes
0 votes

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

Answer:

Related questions

3 votes
3 votes
2 answers
2
8 votes
8 votes
2 answers
3
1 votes
1 votes
3 answers
4