+ 1

In Array of union last member doesn't over write when trying to print but in union it does why?

#include <stdio.h> union type { int i_val; float f_val; char ch_val; }; int main() { union type arr[3]; arr[0].i_val = 42; arr[1].f_val = 3.14; arr[2].ch_val = 'x'; printf("1st element is %d, 2nd is %f, and the 3rd is %c", arr[0].i_val, arr[1].f_val, arr[2].ch_val); return 0; } https://code.sololearn.com/cN91IUD6gQQx/?ref=app

8th May 2020, 2:25 AM
karthik bynagari
karthik bynagari - avatar
1 Answer
+ 3
This is because sharing of memory happens in union, not in array. When you define an array of union then it is just simmilar to defining multiple union variables.
8th May 2020, 2:45 AM
Arsenic
Arsenic - avatar