Structures and Unions Flashcards
what is the struct data type?
what are some of its features
The struct data type is a data type that is used to store a collection of related data items.
Each struct has its own namespace / scope
The name of structs and the name of identifiers are distinct, this means that the name for a struct can be used as the name for a variable.
How are variables declared in the struct arranged in the main memory?
The variables declared in the struct are stored in the main memory in the same order they are declared inside the struct.
2 ways to initialize a struct
- right after the declaration
struct {
…..
} part1 = { 1, 2, 3 }; // don’t have to use designators
- struct Data data = {.number = 123, .name = “Sdfs”}
What happens when you don’t initiate a struct, what will it contain?
Just like arrays, all members are set to 0.
What happens when you initialize only one member inside a struct?
All other members are set to 0
Which has more precedence, the period operator or the &?
The period operator has more precedence than the & operator
How does the assignment work for structures?
When one structure is assigned to another structure, all the members are copied into the other structure. Even arrays are deep copied.
What are the operators that are not valid for structures?
The ==, != etc are not valid for structs in C
What are unions?
What are some of the features of unions?
A union is a data type like struct and it can hold one or more members of different types.
The compiler only allocates memory for the largest of the types and this will overlay any other member within the union.
Changing/ assigning the value of one variable changes the value of all the variables
What are the applications of unions?
- Saving space
- Mixed data structures
Why and how are tags used in Unions?
Once a member has been assigned inside a union, it is indistinguishable from all the other members. In order to distinguish which member contains a meaningful value, a tag is used.
In order to use a union with a tag, a struct is defined and the tag can be a variable inside the struct and a union can also be a member of the struct.