Skip to main content

Posts

Structure & Union Example

In the following example try to find out difference between Structure & Union structemp.c main() { struct employee { int code; char name[15]; }emp[2]; int i; printf("Enter two Employee Details\n"); for(i=0;i<2;i++) { printf("Code:"); scanf("%d",&emp[i].code); printf("Name:"); scanf("%s",emp[i].name); } printf("\nGiven Employee details are\n"); printf("Code\tName"); for(i=0;i<2;i++) printf("\n%d\t%s",emp[i].code,emp[i].name); } For the above program, the output as follows In the above program just replace the keyword struct with union and see what happen, the output as follows while accepting there is no problem with the code, but while displaying it is displayed some garbage value. So this is not right example to highlight the importance of the union. In this case, I try to explain this situation with an exact example,  I want
Recent posts

Difference between Structure and Union

Structure & Union both are users define data types. But the difference between structure and union is in case of structure each and every member can take its own memory location. For example, to maintain the employee details like code, name define a structure as follows          struct employee          {                int code;                char name[15];           };  In the above, the size of the structure is  17 bytes, how we will see int data type size in C-Language is 2 bytes and char data type is 1 byte. For the array name, the size is 15. So the size of name is 15 bytes. Totally it  2 + 15 = 17 bytes. In case of  the union, it will take the common memory location which is highest one in members.  For example if we consider same example        union employee       {              int code;              char name[15];       }; In the above, the highest size member is name with the size 15 bytes.  If this is the situation where code data is store