This blog is under construction

Tuesday, 23 July 2013

C program to find the size of structure and union without using sizeof operator

Write a C program to determine the size of structure and union without using sizeof operator.


  #include <stdio.h>

  /*
   * size of structure is equal to the size of
   * all members of the given structure.  So,
   * the size of struct student is 44 bytes
   */
  struct student {
        char name[32];  // 32 bytes
        int rollNo, rank; // 4 + 4 bytes
        float average; // 4 bytes
  };

  /* 
   * size of union is equal to the size of
   * large data element.  Here, the size of
   * name is the largest(32 bytes).  So, the
   * size of union teacher is 32 bytes.
   */
  union teacher {
        char name[32]; // 32 bytes
        int empID; // 4 bytes
        float salary; // 4 bytes
  };

  int main() {
        struct student *s1;
        union teacher *t1;
        int structSize, unionSize;

        /* assigning NULL to the pointers s1 and t1 */
        s1 = t1 = 0x0;

        /*
         * advance pointers s1 and t1 to get the size
         * of given structure and union.
         */
        structSize =(int)(s1 + 1);
        unionSize = (int)(t1 + 1);

        /* print the result */
        printf("Size of structure student is %d\n", structSize);
        printf("Size of union teacher is %d\n", unionSize);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Size of structure student is 44
  Size of union teacher is 32


No comments:

Post a Comment