Structs and Unions - scuacmw/Intro_to_C_and_Terminal_Workshop GitHub Wiki
What is a struct?
A struct is a collection of values called members that form a single unit or entity. Unlike arrays, structs can hold members of different types. This is very important as arrays are more rigid, in that they only hold one data type. But with structs, we can hold multiple different data types in one, which allows for more dynamic code.
struct info {
int number;
char character;
char string[10];
int array[10];
};
Declaring Struct Variables
struct info inf;
struct info *p;
Memory is allocated for inf, and it's a collection of variables called member variables.
To access individual members:
p = &inf;
inf.number = 2;
inf.character = ‘A’;
What is a union?
A union is a data structure that overlays components in memory, which allows for multiple interpretations of data. It is used for saving space in situations where a data object needs to be interpreted in many different ways. It works the same as a struct:
union info {
int number;
char character;
char string[10];
int array[10];
};
Declaring unions and structs can also be written using typdef.
typedef union {
int number;
char character;
char string[10];
int array[10];
} INFO;
To access a member, you would do:
INFO inf;
inf.number = 1;
Helpful site for structs and unions
https://www.geeksforgeeks.org/difference-structure-union-c/