Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 135 ยท Structures and Unions

Arrays of Structures and Nested Structures

Learn to build tables of records in C with arrays of structures, search and total them, sort them with qsort by one or more keys, and nest structs inside structs.

A single struct describes one thing: one book, one product, one employee. Programs usually deal with many of them at once: a catalog, an inventory, a class list. The natural C representation is an array of structures, where each element is a complete record. It's the in-memory version of a spreadsheet or a database table, and you'll use it constantly.

This lesson shows how to declare and initialize tables of records, loop over them to search and summarize, sort them with the standard library's qsort (by one key and by several), and model richer data by nesting structs inside other structs. You should already be comfortable with Structures and Structures and Pointers.

Declaring and initializing a table

An array of structs is declared like any other array; the element type just happens to be a struct. The initializer is a list of struct initializers, and designated initializers work inside each element:

C
struct product {
    char sku[8];
    const char *name;
    int stock;
    double price;
};

struct product inventory[] = {
    {"A100", "Desk lamp", 12, 34.99},
    {"B220", "Notebook", 140, 3.49},
    {.sku = "C310", .name = "Headphones", .stock = 0, .price = 79.00},
};

When you leave the size empty, the compiler counts the elements. To get the count back, use the familiar sizeof trick: sizeof inventory / sizeof inventory[0]. That works here because inventory is a real array in this scope. Once it's passed to a function it decays to a pointer, so functions always receive the count as a separate parameter.

Each element is a whole struct, so inventory[1] is a struct product and inventory[1].price is a double. The subscript and the dot are applied left to right.

Looping over records

Most work on a table is a loop: find a record, total a column, filter rows. Passing the table as const struct product * with a count makes those functions reusable for any table:

C Searching and summarizing a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The report prints four aligned rows, marks the headphones as out of stock, and totals 1270.98. Two patterns are worth copying:

  • Return a pointer to the found element, or NULL. The caller gets direct access to the record (no copy), and NULL cleanly means "not found". Returning an index works too, with a sentinel such as (size_t)-1 or a separate bool.
  • Take &inventory[i] once and use p-> inside the loop body. It's shorter than repeating inventory[i]. and makes it obvious that every line works on the same record.

Sorting records with qsort

The standard library's qsort (from <stdlib.h>) sorts any array, including arrays of structs. It needs four things: the array, the element count, the element size, and a comparison function that takes two const void * pointers to elements and returns a negative number, zero or a positive number. The comparison function is a function pointer; inside it, you convert the void * arguments back to your struct type.

C Sorting a table by different keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Amara wins in 19:35; sorted by name, Amara comes first and Yuki last; and the final ordering groups runners by country with the fastest first: Mateo before Sofia for ESP, Kenji before Yuki for JPN, Amara before Brian for KEN.

Some details matter here:

  • Don't compare numbers with subtraction. return x->seconds - y->seconds; looks neat but can overflow for large or negative values, which is undefined behavior and produces a wrong order. The expression (a > b) - (a < b) yields exactly -1, 0 or 1 and never overflows.
  • Multiple keys are just a chain: compare the first key, return if it differs, otherwise fall through to the next. Reusing by_time as the tie-breaker keeps the code short.
  • qsort is not stable. Elements that compare equal may end up in any order. If you need a stable result, add a final tie-breaker (such as an original index stored in the struct).

The qsort and bsearch lesson goes deeper into comparators, including sorting strings and searching sorted tables with bsearch.

Nested structures

A struct member can itself be a struct. That lets you build data from reusable pieces: a struct date used inside struct employee, a struct point used inside struct rectangle. You access inner members by chaining dots, staff[0].hired.year, and designated initializers nest the same way.

C Structs inside structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program finds that Tomas Novak (hired 2015-11-02) has served longest, a few weeks ahead of Lea Fischer. The three initializer styles in staff are equivalent: nested designated initializers, nested positional ones, and flat paths like .hired.year = 2015. The first style is usually the clearest.

Nesting a struct by value, as here, embeds the whole inner struct inside the outer one. Copying an employee copies its date and address too, and sizeof(struct employee) includes them: 72 bytes on our system. (Structs can also contain invisible padding bytes; this one happens to need none.) The alternative is a pointer member, such as const struct department *dept;, which lets many employees share one department record. Embed when the inner data belongs to exactly one outer record; point when it's shared or optional.

Arrays inside structs, structs inside arrays

You can combine both directions freely. A struct can hold an array member, and that array can even hold structs:

C
struct team {
    char name[32];
    struct runner members[5];
    size_t member_count;
};

Then league[2].members[0].seconds reads the time of the first member of the third team. Read it left to right: pick an element, pick a member, pick an element, pick a member. If such expressions get long, take a pointer to the inner record first: const struct runner *r = &league[2].members[0];.

Note the member_count field: a fixed-size array member always has room for 5 runners, so the struct needs to remember how many are actually used. When the number varies widely, store a pointer to a dynamic array instead.

Sorting pointers instead of records

qsort moves whole elements around. For small structs that's fine, but if each record is large (say 500 bytes), every swap copies a lot of memory. A common technique is to sort an array of pointers to the records. The records stay put; only 8-byte pointers move. It also lets you keep several orderings of the same data at once.

C Sorting an index of pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The index lists Krakow, Oslo, Lisbon and Tallinn, while cities[0] is still Lisbon. The comparator is the tricky part: qsort passes pointers to the elements, and each element is itself a pointer, so a really is a const struct city *const *. Dereferencing once gives the record pointer. Getting this level of indirection wrong is the most common qsort bug, and it compiles silently because everything goes through void *.

Arrays of structs versus parallel arrays

Older code sometimes stores a table as parallel arrays: names[i], ages[i] and scores[i] together describe person i. It works, but nothing keeps the arrays in step. Sorting one and forgetting another scrambles the data, and every function needs all the arrays as parameters. An array of structs keeps each record together, so it should be your default.

(Performance-critical code, such as game engines and numeric libraries, sometimes deliberately uses a "structure of arrays" layout, because looping over one field across many records is more cache-friendly. That's an optimization to choose on purpose after measuring, not a starting point.)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. struct item list[] = {{"pen", 3}, {"cup", 1}, {"map", 2}}; Inside the same function, what is sizeof list / sizeof list[0]?

    The compiler sized the array from its three initializers, and the division of total bytes by element bytes gives the element count.
  2. 2. Why is return x->score - y->score; a risky qsort comparator?

    qsort accepts any negative or positive value, but the subtraction itself can overflow. (a > b) - (a < b) is safe.
  3. 3. You sort an array of struct city * with qsort. What does the comparator receive in its const void *a parameter?

    qsort always passes pointers to elements. When the elements are pointers, a points to a pointer, so you must dereference once to reach the record.
  4. 4. struct employee { const char *name; struct date hired; }; Which line sets the hire year of the second employee in staff?

    Pick element 1 of the array, then its hired member, then that struct's year member. No pointers are involved, so only dots are used.
  5. 5. Two runners have the same time and you sort by time with qsort. Which statement is true?

    qsort may reorder equal elements. Add a tie-breaker key if a predictable order matters.

Summary

  • An array of structs is a table of records: struct product inventory[] = {{...}, {...}};. Get the count with sizeof array / sizeof array[0] before the array decays, and pass the count to functions.
  • table[i].member picks a record and then a field. Search functions commonly return a pointer to the found record or NULL.
  • qsort(array, count, sizeof array[0], compare) sorts records. Comparators convert the const void * arguments to the struct type, avoid overflow-prone subtraction, and chain keys for multi-key sorts. qsort isn't stable.
  • Structs can nest by value (staff[i].hired.year) or by pointer (shared or optional data). Designated initializers nest naturally.
  • Sorting an array of pointers moves only pointers and can keep several orderings of the same records; the comparator then receives pointers to pointers.
  • Prefer arrays of structs over parallel arrays, which easily fall out of sync.

Next: Unions, where several members share the same memory, and tagged unions let one type hold different kinds of values.