union occupies less memory than structure
union variable can store one value at a time & same memory location, can be used to store multiple types of data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include<stdio.h> #include <string.h> struct Student_Structure { char name[30]; char section[1]; int rollno; int Class; } s1; union Student_union { char name[30]; char section[1]; int rollno; int Class; } u1; int main() { printf("\n 1st difference is union occupies less memory than structure"); printf("\nsizeof structure : %d\n", sizeof(s1)); printf("sizeof union : %d\n", sizeof(u1)); printf("\n 2nd difference is union variable can store one value at a time & same memory location, can be used to store multiple types of data."); // store student name, rollno, class & section using structure variable s1 strcpy(s1.name, "Aditya"); s1.rollno = 12345; s1.Class = 12; strcpy(s1.section, "A"); printf("\n Student details using structure"); printf("\n Name = %s", s1.name); printf("\n Rollno = %d", s1.rollno); printf("\n Class = %d", s1.Class); printf("\n Section = %s", s1.section); // store student name, rollno, class & section using union variable u1 strcpy(u1.name, "Aditya"); u1.rollno = 12345; u1.Class = 12; strcpy(u1.section, "A"); printf("\n Student details using union"); printf("\n Name = %s", u1.name); printf("\n Rollno = %d", u1.rollno); printf("\n Class = %d", u1.Class); printf("\n Section = %s", u1.section); return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 1st difference is union occupies less memory than structure sizeof structure : 40 sizeof union : 32 2nd difference is union variable can store one value at a time & same memory location, can be used to store multiple types of data. Student details using structure Name = Aditya Rollno = 12345 Class = 12 Section = A Student details using union Name = A Rollno = 65 Class = 65 Section = A |