diff options
author | loshprung <lshprung@scu.edu> | 2020-01-24 11:16:42 -0800 |
---|---|---|
committer | loshprung <lshprung@scu.edu> | 2020-01-24 11:16:42 -0800 |
commit | 7f939ea40a4451ab1320ac508d2922fc3b20ac19 (patch) | |
tree | 818e2db323ab85a64e3001bab0933c93636a9353 /01-24.md | |
parent | 272aeb46a56e3875e639c1f263f5134ea028af06 (diff) |
Post-class 01/24
Diffstat (limited to '01-24.md')
-rw-r--r-- | 01-24.md | 102 |
1 files changed, 102 insertions, 0 deletions
diff --git a/01-24.md b/01-24.md new file mode 100644 index 0000000..67a9792 --- /dev/null +++ b/01-24.md @@ -0,0 +1,102 @@ +[\<- Notes 01/17](01-17.md) + +--- + +# Unions + +- A union is a data structure that overlays components in memory + - Allows one chunk of memory to be interpreted in multiple ways +- The union is used for saving space + - In situations in which one needs a data object that can be interpreted in a variety of ways + +Declaration Outline: + +``` +union union_t{ + variable declaration; + variable declaration; + ... +}; +``` + +Alternatively, you can use `typedef`: + +``` +typedef union{ + variable declaration; + variable declaration; + ... +} UNION_T; +``` + +Both examples above are type definitions and do not allocate memory + +Union Example: + +``` +typedef union{ + int age; + char artist[20]; +} ART_INFO; +``` + +- Defines a Union Type + - The name of `ART_INFO` is the union tag + - The identifiers are called members (like in structures) + - Members can be any valid C data type + - With this example, `ART_INFO` can be used like int, char, etc. + +``` +ART_INFO info; +``` + +- `info` is a variable +- `info` **does not have both components** + - Amount of memory allocated depends on the largest component in the union +- the member variables are accessed using the dot operator + +``` +info.age = 2000; +``` + +or + +``` +strcpy(info.artist, "Michelangelo"); +``` + +- Member names are local and not known outside the union + +- Like structures, unions can be declared as an array of unions: + +``` +ART_INFO info_array[20]; + +info_array[0].age = 1000; +``` + +- Pointers to unions can be declared + - Like with structures, arrow operator is used to access members for pointers + +- Union example in a Structure: + +``` +typedef union{ + int age; + char artist[20]; +} ART_INFO; + +typedef struct{ + char name[20]; + int class; + ART_INFO info; +} ART_CLASS; + +ART_CLASS class_array[4] = +{{"Mask of Agamemnon", 0, .info.age = 3500}, +{"Mona Lisa", 1, .info.artist = "Leonardo da Vinci"}, +{"Nok rider and horse", 0, .info.age = 2000}, +{"Pieta", 1, .info.artist = "Michelangelo"}}; +``` + +- Be careful not to reference an invalid member in your union! |