Records

The structured type with named and typed fields: definition, dot notation access, array of records, nested records.

  • 22 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Record: what is it?

    Show the answer

    A composite piece of data made of several named values, possibly of different types, grouped under a single name.

    A student (name, age, average) is a record. In C it is a struct; in Java, a class or a record; in Python, a data class.

  • What does this program print?

    ```python
    from dataclasses import dataclass

    @dataclass
    class Student:
    name: str
    marks: list

    students = [Student("Ana", [12, 15]), Student("Ben", [9, 14]), Student("Cleo", [17, 11])]
    print(students[1].marks[0])
    `

    • 9
    • 14
    • 12
    • Ben
    Show the answer

    9

    students[1] is the second student (Ben), .marks his list [9, 14], [0] the first mark: 9. 14 would be marks[1], 12 the first mark of the first student.

  • In C, a record is declared with the keyword … and a field is accessed with the … character, as in p.x.

    Show the answer

    In C, a record is declared with the keyword struct and a field is accessed with the dot character, as in p.x.

    Python and Java use the same dot notation for a field or an attribute. In C, with a pointer to the record, write p->x.

  • Field: what is it?

    Show the answer

    A named and typed value that is part of a record.

    A field is identified by its name, whereas an array cell is identified by its number. In an array, all the cells have the same type; this is not required of fields.

  • A program keeps two parallel arrays, names and ages. After sorting names alphabetically, the ages no longer match the right people. Which solution fixes the problem at its root?

    • Also sort ages, with the same algorithm, but on its own values
    • One array of Person(name, age) records, sorted as a block
    • Sort ages first, then names, so the indices line up
    • A single array alternating a name, an age, a name, an age
    Show the answer

    One array of Person(name, age) records, sorted as a block

    Parallel arrays rely on a convention: cell i of each array concerns the same person. Sorting only one breaks it. A record keeps name and age together, and moving a cell moves both.