Unions in C are offer a choice of multiple members, each of which is mapped to the same memory location. If you set more than one, you're corrupting the memory of the other members.
Beyond this, Longest.aa
is uninitialized, so you're printing a garbage value.
It sounds like you'd like a struct, which offers a "vertical" collection of members that can all be set and accessed simultaneously (as you're doing with char_struct
). The size of the struct is at least the sum of all of its member sizes plus any cache size alignment the compiler adds.
Here's a sample program illustrating a few of these points:
#include <stdio.h>
struct char_struct {
unsigned char x;
unsigned char y;
unsigned char z;
};
struct longest_t {
unsigned long int aa;
struct char_struct b;
};
int main() {
unsigned long int bb = 0;
struct longest_t longest;
longest.b.x = 2;
longest.b.y = 3;
longest.b.z = 4;
longest.aa = 42;
bb = longest.aa;
printf("%ld\n", bb);
printf("%d %d %d\n", longest.b.x, longest.b.y, longest.b.z);
printf("longest_t size: %lu\n", sizeof(struct longest_t));
printf("char_struct size: %lu\n", sizeof(struct char_struct));
printf("ul int size: %lu\n", sizeof(unsigned long int));
return 0;
}
A run on my machine shows:
42
2 3 4
longest_t size: 16
char_struct size: 3
ul int size: 8
You may wish to typedef your structs, and I suggest more semantically-meaningful variable names, although I do realize this is an example program. There are a few conventions for struct names, but typically variable names are not upper camel cased like Longest
.