Union Memory Sharing
C
Hard
4 views
Problem Description
Create a union containing an int, float, or char array. Store a value in one member, then read it from the other. What value will be returned, and why (concept of memory overlap)?
Official Solution
#include <stdio.h>
union Data {
int i;
float f;
char str[4];
};
int main() {
union Data data;
/* Store int value */
data.i = 65;
printf("After storing int:n");
printf("data.i = %dn", data.i);
printf("data.f = %fn", data.f);
printf("data.str = %snn", data.str);
/* Store float value */
data.f = 65.5;
printf("After storing float:n");
printf("data.i = %dn", data.i);
printf("data.f = %fn", data.f);
printf("data.str = %snn", data.str);
/* Store string */
data.str[0] = 'A';
data.str[1] = 'B';
data.str[2] = 'C';
data.str[3] = '