This blog is under construction

Saturday, 19 May 2012

sizeof struct vs union

sizeof() is a unary operator which can be used to find the size of any data element.  Size of structure is equal to the sum of size of all data members in a structure.  Whereas, size of union is equal to the size of largest data member in a union.

Consider the following example,
struct value {
         float y;
         char ch;

union value {
         float y;
         char ch;

Size of struct value is 5 bytes(size of float is 4 byte + size of char is 1 byte)
Size of union value is 4 bytes(y is the largest data member in the union value)

Example C program to illustrate the difference between the size of union and structure:

  #include <stdio.h>
  struct student {
        char name[100];
        int age;
        float height;

  union book {
        char name[100];
        char author[200];
        int pages;
        float price;

  int main() {
        struct student s1;
        union book b1;
        printf("Size of int: %d\n", sizeof(int));
        printf("Size of float: %d\n", sizeof(float));
        printf("Size of double:%d\n", sizeof(double));
        printf("Size of char: %d\n", sizeof(char));
        printf("Structure size: %d\n", sizeof(s1));
        // union size => size of largest data member
        printf("Union size: %d\n", sizeof(b1));
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Size of int: 4
  Size of float: 4
  Size of double:8
  Size of char: 1
  Structure size: 108
  Union size: 200

No comments:

Post a Comment