
CS485G Spring 2015 32
34 Unions
1. Snow day: 3/6/2015
2. Lecture 18, 3/9/2015
3. A union type is like a struct, but the fields all start at offset 0, so
they overlap.
4. This method allows us to view the same data as different types.
5. It also lets us look at individual bytes of numeric types to see the
byte ordering.
6. Example:
1 union {
2 char c[8]; // 8
*
1 = 8 bytes
3 short s[4]; // 4
*
2 = 8 bytes
4 int i[2]; // 2
*
4 = 8 bytes
5 long l[1]; // 1
*
8 = 8 bytes (on i86_64)
6 float f[2]; // 2
*
4 = 8 bytes
7 } dw;
8 dw.f[0] = 3.1415;
9 printf("as float: %f; as integer: %d;\n"
10 "as two shorts: %d, %d\n",
11 dw.f[0], dw.i[0], dw.s[0], dw.s[1]);
Result:
as float: 3.141500; as integer: 1078529622;
as two shorts: 3670, 16457
35 Linux x86 memory layout
1. Simplified version of allocation of 4GB virtual space
start name purpose properties
0 unused prevent errors no access
0x08000000 text program read-only
data initialized data read, write; static size
bss uninitialized data read, write; static size
heap allocatable data read, write; grows up
stack activation records read, write; grows down
0xC0000000 kernel kernel code, shared no access
Kommentare zu diesen Handbüchern