summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorloshprung <lshprung@scu.edu>2020-01-24 11:16:42 -0800
committerloshprung <lshprung@scu.edu>2020-01-24 11:16:42 -0800
commit7f939ea40a4451ab1320ac508d2922fc3b20ac19 (patch)
tree818e2db323ab85a64e3001bab0933c93636a9353
parent272aeb46a56e3875e639c1f263f5134ea028af06 (diff)
Post-class 01/24
-rw-r--r--01-17.md4
-rw-r--r--01-24.md102
2 files changed, 106 insertions, 0 deletions
diff --git a/01-17.md b/01-17.md
index 48a3b00..7c59be7 100644
--- a/01-17.md
+++ b/01-17.md
@@ -126,3 +126,7 @@ void fun1(struct simple *s){
```
- This is the same idea as passing variables as copies versus as pointers to memory
+
+---
+
+[-> Notes 01/24](01-24.md)
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!