Structure Sorting Lab and Quiz- Embedded C Programming Course Online

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Structure and Union

Structure Sorting Lab and Quiz

Finish the chapter with a tie-breaker lab on structure sorting in C, then test yourself with a quiz and real embedded C interview questions.

Practice makes the lessons stick. In this closing lecture of the structure sorting in C series we build a small priority queue ordering with qsort and a three-level comparator, then you take a ten-question quiz and read twelve interview questions that come up in embedded C programming interviews. Everything here belongs to our free C programming course, a free C tutorial path that also works as a free embedded C course for beginners.

What You Will Learn

  • How to combine several keys in one comparator so ties are resolved predictably
  • Why you should not rely on qsort keeping equal items in their original order
  • How to read and predict the output of structure-sorting code
  • How to answer common interview questions on structures, arrays and sorting

Prerequisites

Lectures 21 to 24 of this chapter: arrays of structures in functions, derived fields, sorting by swapping or pointers, and comparators for qsort.

Lab: Structure Sorting in C With Tie-Breakers

Imagine an embedded device with a queue of pending events. The most severe event must run first. Among events of equal severity, the one raised earlier goes first. If even the raise time matches, the lower identifier wins. That is three keys with three levels of priority, and the last key guarantees that no two events ever compare as equal. A comparator with no ties produces the same order on every machine and every library version.

Decision chain inside the comparator
Step 1severity differs? → higher severity first, stop
Step 2tick differs? → earlier tick first, stop
Step 3id differs → lower id first (always decides)
#include <stdio.h>
#include <stdlib.h>

struct event {
    int id;
    int severity;   /* higher = more urgent */
    int tick;       /* when it was raised   */
};

static int three(int a, int b)
{
    return (a > b) - (a < b);   /* -1, 0 or +1, never overflows */
}

/* severity descending, then tick ascending, then id ascending */
static int cmp_event(const void *x, const void *y)
{
    const struct event *a = x, *b = y;
    int r;

    if ((r = three(b->severity, a->severity)) != 0) return r;
    if ((r = three(a->tick,     b->tick))     != 0) return r;
    return three(a->id, b->id);
}

int main(void)
{
    struct event q[] = {
        { 101, 2, 40 }, { 102, 3, 35 }, { 103, 2, 10 },
        { 104, 3, 35 }, { 105, 1, 5  }, { 106, 2, 40 }
    };
    size_t n = sizeof q / sizeof q[0];

    qsort(q, n, sizeof q[0], cmp_event);

    printf("id   sev  tick\n");
    for (size_t i = 0; i < n; i++)
        printf("%d  %d    %d\n", q[i].id, q[i].severity, q[i].tick);
    return 0;
}

Build and Run

$ gcc -std=c17 -Wall -Wextra -o ex25 ex25.c
$ ./ex25
id   sev  tick
102  3    35
104  3    35
103  2    10
101  2    40
106  2    40
105  1    5

Reading the Result

Events 102 and 104 both have severity 3 and tick 35, so steps 1 and 2 cannot separate them; step 3 puts 102 first. Events 101 and 106 tie the same way on severity 2 and tick 40, and the identifier decides again. Event 103 has the same severity but an earlier tick, so it precedes them both. Without the third step, 102 and 104 would compare as equal and qsort would be free to output them in either order.

Try It Yourself

  1. Change the comparator so that the lowest severity comes first. Which single line changes?
  2. Add a fourth member source and make it the second key. Re-run and explain the new order.
  3. Remove the final id comparison and run the program several times with extra duplicate events. Does the output ever change?

Rule of thumb: if the order of equal items matters to your product, never leave equal items possible. Add keys until every pair of records can be told apart.

Structure Sorting in C Quiz

Choose an answer for each question, then open the answer line to check yourself.

  1. When you pass the name of an array of structures to a function, what does the function receive?

    • A. A full copy of the array
    • B. A pointer to the first element
    • C. Only the first structure, by value
    • D. The size of the array
    Show answer

    B. Only the address of element zero is copied.

  2. Inside the callee, with a parameter declared struct item list[], what does sizeof(list) give?

    • A. The size of the whole array
    • B. The size of one element
    • C. The size of a pointer
    • D. Zero
    Show answer

    C. The parameter is a pointer, so you get its size, for example 8 bytes on a 64-bit system.

  3. Which operator can compare two whole structures in C?

    • A. ==
    • B. <
    • C. Both A and B
    • D. None of these
    Show answer

    D. Structures must be compared member by member.

  4. A structure holds one char followed by one int. On a typical machine its size is:

    • A. 5
    • B. 8
    • C. 4
    • D. 1
    Show answer

    B. Three padding bytes follow the char so the int is aligned on a 4-byte boundary.

  5. In a grading ladder with thresholds 4100, 3900 and 3600, why test 4100 first?

    • A. It is the largest number
    • B. Later tests only run if earlier ones fail, so the strictest must come first
    • C. The compiler requires it
    • D. It runs faster
    Show answer

    B. Starting with the loosest rule would make every value match it.

  6. What type of arguments does a qsort comparator receive?

    • A. Two structures by value
    • B. Two const void * pointers to elements
    • C. Two integers
    • D. An element and an index
    Show answer

    B. You cast them back to your own element type inside the function.

  7. After sorting an array of pointers to structures, what happens to the original array of structures?

    • A. It is also sorted
    • B. It is deleted
    • C. It is unchanged
    • D. It is copied
    Show answer

    C. Only the pointers move.

  8. What does (a > b) - (a < b) evaluate to when a is smaller than b?

    • A. 1
    • B. 0
    • C. -1
    • D. Undefined
    Show answer

    C. The first comparison is 0 and the second is 1, so the result is -1.

  9. A structure emp contains a member joined of type struct date with a member year. How do you read the year?

    • A. emp->year
    • B. emp.year.joined
    • C. emp.joined.year
    • D. joined.emp.year
    Show answer

    C. Chain the dot operator from the outer structure inward.

  10. Predict the output:

    struct p { int v; };
    void inc_arr(struct p a[]) { a[0].v++; }
    void inc_one(struct p x)   { x.v++; }
    
    int main(void)
    {
        struct p t[2] = { {1}, {1} };
        inc_arr(t);
        inc_one(t[1]);
        printf("%d %d\n", t[0].v, t[1].v);
        return 0;
    }
    • A. 1 1
    • B. 2 2
    • C. 2 1
    • D. 1 2
    Show answer

    C. The array function edits the caller’s element, while inc_one only edits its private copy. Output: 2 1.

Embedded C Interview Questions on Structure Sorting in C

Structure sorting in C and its neighbours, padding and array parameters, appear regularly in firmware interviews. Try answering aloud before you open each one.

1. Is an array of structures passed by value or by reference?

C passes everything by value, but an array name decays to a pointer to its first element, so the function works on the caller’s data. A single structure passed directly is copied.

2. Why must you pass the element count separately?

Inside the function the parameter is only a pointer, so the compiler no longer knows how many elements exist. sizeof cannot recover it.

3. What is structure padding and why does it exist?

The compiler inserts unused bytes so each member sits at an address suited to its type. This makes access faster or even possible on strict architectures. Ordering members from largest to smallest reduces waste.

4. How would you sort an array of large structures cheaply?

Build an array of pointers to the structures and sort that array. Swapping pointers moves far fewer bytes than swapping records.

5. What is wrong with returning a – b from a comparator?

The subtraction can overflow, which is undefined behaviour for signed integers and can flip the sign. Use (a > b) - (a < b).

6. Is qsort stable?

The C standard does not guarantee it. Add tie-breaking keys so no two elements compare equal.

7. How do you protect a table from accidental modification inside a function?

Declare the parameter with const, for example const struct item *list. Writes through it will not compile.

8. Can you compare two structures with memcmp?

It is unreliable because padding bytes have indeterminate values, so two equal-looking structures can differ. Compare member by member.

9. What does a designated initializer do?

It names the member being initialised, such as .id = 3. Unnamed members become zero, and the code stays correct if the structure layout changes.

10. When would you store a derived value in the structure instead of computing it?

When it is read often, changes rarely and computing it is costly, a common case on slow microcontrollers. The risk is staleness, so recompute whenever the source members change.

11. Why is a nested structure not the same as a pointer to a structure?

A nested structure is stored inline inside the outer one and is reached with dots. A pointer member holds an address and needs an arrow or dereference, plus valid memory behind it.

12. How can the sort key be chosen at run time?

Keep a table that maps each key name to a comparator function pointer and pass the selected pointer to qsort.

Common Mistakes and Troubleshooting

  • Leaving ties unresolved and then being surprised by an order that changes between platforms
  • Comparing only part of a date, such as the day, when sorting records by date
  • Using the pointer size instead of the structure size as the third argument of qsort
  • Printing the original array after a pointer sort and expecting it to be ordered

Best Practices, Performance and Security

Final checklist for structure arrays

  • Pass base pointer plus count, and mark read-only parameters const
  • Reset accumulators inside the function that fills derived fields
  • Prefer sorting pointers for big records
  • Write comparators that never overflow and never leave ties
  • Check every external count or date before indexing or sorting on it

Summary and Key Takeaways

  • Array parameters are pointers, so functions edit the caller’s structures
  • Derived fields turn raw samples into decisions, but must be recomputed when sources change
  • Sorting can swap records or pointers; pointers win for large records
  • A three-level comparator with a unique last key gives a deterministic order
  • Comparators belong in tables of function pointers when the key must be chosen at run time

Conclusion: Structure Sorting in C

You have now covered the full path from passing a table of structures into a function, through computing values in a loop, to ordering the table by any key you like. Structure sorting in C ties them together, and these skills are the daily bread of embedded C programming: register maps, sensor tables, event queues and firmware catalogues are all arrays of structures. Keep experimenting with the programs from this chapter, and continue with the next chapter of the free C programming course when you are ready.

Frequently Asked Questions

Do I need to memorise the qsort signature?

It helps. The order is array, count, element size, comparator.

Can the same comparator be reused for bsearch?

Yes, as long as the array is sorted with the same ordering. The key argument is passed as the first pointer.

Is this free C programming course suitable for beginners?

Yes. Each lecture explains the idea in plain words, then shows original code with the expected output.

Will these topics help in embedded interviews?

They cover some of the most frequently asked areas: structures, pointers, padding and sorting.

What should I study after structures?

Unions, enumerations and bit fields come next in this chapter family, followed by file handling and the preprocessor.

Continue Your Free Embedded C Course

Chapter complete. Move on to the next topic in our free C tutorial series for embedded systems students.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →