in Programming
1,263 views
10 votes
10 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
in Programming
by
1.3k views

4 Comments

^Yes
0
0

" Given an int array Arr "  refers to one element of an array and not the entire array  . That is ambiguous.

Something is not right.

1
1
No, arr is an array - not array element.
0
0

2 Answers

16 votes
16 votes
Best answer

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
by

4 Comments

sir, in stmt one, the last word is 'elements' not element so we should not consider the case of single element. so it should be true??
1
1
That's too small a reason. Element's' is used to give the possibility of multiple elements. Don't think using this we can exclude 'single element'.
1
1
sir  "In union we are supposed to use only one of them at a time " is it true that one of them should be anyone bt space given to union should be max of (int or char ) always ??            //a/c to aboove example
0
0
yes. And that is why space taken is maximum of all.
1
1
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