Chapter Summary
This chapter explored complex aggregate types that combine arrays and structs to organize related data efficiently. Two primary approaches were examined: parallel arrays and arrays of structs, each with distinct advantages and trade-offs.
Key Concepts
Structs with Array Members
- Definition: A struct that contains one or more array data members, allowing arrays of information to be packaged as a single unit
- Declaration Syntax:
struct StructName
{
datatype arrayMember[CAPACITY];
// other members
}; - Initialization: Array members are initialized using nested braces within the struct initializer
- Access Syntax: Use dot (
.) or arrow (->) operator to access the array, then use subscript notation to access individual elements- Example:
student.quizzes[0]orptrStudent->quizzes[0]
- Example:
- Advantage: Packages related arrays together, improving code organization
Parallel Arrays
- Definition: Multiple arrays where data stored at the same index across arrays represents a single logical entity
- Example: Separate arrays for student numbers, midterm scores, and final scores where
studentNumber[i],midterm[i], andfinal[i]all refer to the same student - Advantages: Simple to understand for small amounts of related data
- Disadvantages: Becomes cumbersome with many pieces of related data; requires careful synchronization when modifying data (example: sorting requires swapping in all arrays simultaneously)
- Use Case: Appropriate when storing only a few related pieces of information
Arrays of Structs
- Definition: An array where each element is a struct, allowing multiple instances of structured data to be stored and accessed uniformly
- Declaration Syntax:
struct StructName arrayName[CAPACITY]; - Initialization Syntax: Nested braces where each outer brace pair initializes one struct element
struct StudentScore students[40] = {
{123456, 63.5, 65.0},
{654321, 70.5, 75.3}
}; - Access Syntax: Use array subscript to access a struct element, then use dot (
.) or arrow (->) to access struct members- Example:
students[0].midtermorptrStudents[0].midterm
- Example:
Advantages of Arrays of Structs Over Parallel Arrays
- Simplicity: A single array declaration replaces multiple parallel array declarations
- Maintainability: Adding new data members requires modifying only the struct definition, not multiple function signatures
- Clarity and Scalability: Functions can operate on complete logical entities (structs) rather than coordinating multiple arrays. No need to synchronize swaps across multiple arrays
- Reduced Errors: Less opportunity for parallel arrays to become "out of sync" during modifications
Working with Arrays of Structs in Functions
- Parameter Declaration:
const struct StructName arrayName[](const prevents unintended modifications) - Accessing Elements: Use array index to select a struct, then member access operator to reach data