0

What is the difference between struct and union in c programming

16th Apr 2022, 4:40 PM
Jeya Sudha G V
2 odpowiedzi
0
A struct holds members that will not be overwritten, a union holds members that share a memory location thus they get overwritten. struct my_data{ char a; int x; } sets in memory 1 byte for the char & 2 or 4 bytes (depending on your system) for the int such: [char a][int x][int x][int x][int x] <-- reserved on stack or heap depending on how you initialize it. union my_data{ char a; int x; } Sets in memory the most memory needed for any of the members and reuses it such: [my_data][my_data][my_data][my_data] <-- used if setting or getting the char or int. Only the last set will be saved. Here is an example for union: #include <stdio.h> #include <stdlib.h> union my_data{ char a; int x; }; int main(void){ union my_data My_Data; My_Data.a = 'c'; printf("char a is = %c\n", My_Data.a); //Both are still valid names. printf("int x is = %i\n", My_Data.x); puts(""); My_Data.x = 5; printf("char a is = %c\n", My_Data.a); //Both are still valid names, but data was overwritten printf("int x is = %i\n", My_Data.x); return 0; } outputs: char a is = c int x is = 99 char a is = int x is = 5
16th Apr 2022, 6:37 PM
William Owens
William Owens - avatar