in Programming in C
665 views
3 votes
3 votes
What is the output of the code given below?

#include <stdio.h>
#include <string.h>
union sample {
    int i;
    float f;
    char c;
    double d;
    char str[20];
};
int main() {
    // union sample sm;
    printf("Memory size occupied by sample : %d", sizeof(union sample));
    return 0;
}

 

in Programming in C
665 views

1 comment

can you describe how 24byte come? why it is increasing 8 to 16 and 16 to 24?
0
0

1 Answer

1 vote
1 vote
Best answer

Note : Size of union is based on the size of the largest member of the union .

In this case size of union is based on the largest variable which is double , suppose size of double is 8 bytes .

But , there is array of characters of size 20 is present . 

then ,

  1. first it allocated 8 bytes. But 8<20
  2. again allocates 8 bytes total is 16 bytes . But 16<20
  3. again allocate 8 bytes total is 24 bytes and 24 is not smaller than 20 

so , all the array of 20 characters can fit in 24 byte .

therefore , ans is 24 bytes in the case of double size is 8 bytes

selected by

4 Comments

This 8+8+8 = 24 Byte is for char str[20] right ?

As char 1 byte so 20*1 = 20 byte so (8 + 8 + 4) + 4 byte extra = 24 byte

Am I right ?
1
1
Yes , it's allocating on basis of double so 4 bytes will be extra .
0
0
can you describe how 24byte come? why it is increasing 8 to 16 and 16 to 24?
0
0
Compiler allocates memory to union on the basis of largest variable here largest variable is double , but also array of character is also present so compiler allocates memory first 8 bytes and checks is it sufficient if not again allocates memory of 8 bytes and again checks is it sufficient.
1
1

Related questions