UPI Study › Courses › Programming in C › Free lessons › Lesson 10.3 Free with a free account
Arrays of Structures in C
Programming in C · Chapter 10: Structures, Unions, and Compound Data ModelingSection 10.3 · lesson 66 of 785 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Pointers to Structures in C →← Defining Structures in CNext lesson: Pointers to Structures in C →
In this lesson
Storing, scanning, and sorting a table of struct records.
- Declare and initialize an array of structs and access members with board[i].score
- Loop over an array of structs using sizeof to count its elements
- Find the record with the highest value by tracking its index
- Sort an array of structs by one member while swapping whole records
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (734 words). Read along, or search it.
Opening Question
Building an Arcade Leaderboard
Every arcade has a leaderboard: a list of players, each with a name and a score. You can already bundle a name and a score into one struct. And you can keep many numbers in an array. Put the two ideas together, and you get an array of structs: the shape behind almost every table of records a program shows. Today you'll build the leaderboard, find the champion, and sort the list.
Declaration
Index First, Then Dot
You declare an array of structs just like an array of ints: the type, a name, and the number of items in square brackets. Here the type is Player, so each of the five elements is a whole player, with its own name and score. To fill it, write one set of braces for each element, inside the outer braces. Now two pieces of syntax combine. board 2 is the third element, a whole Player. Add a dot, and you pick a member inside it. So board 2 dot score reads left to right: the score of element 2. Run it. Kai has 5075. And the whole array takes 80 bytes on this Mac: five players of 16 bytes each, side by side in one block.
Looping
Counting Records With Sizeof
A for loop visits the records one at a time. But first, how many are there? sizeof board divided by sizeof board 0: the size of the whole array, over the size of one element. That's 80 over 16, which is 5. It works only where the array was declared. Inside a function that received the array, board is just an address, as you saw in 8.6. Each pass prints one row, using board i dot name and board i dot score, and adds the score to the total. And watch the condition: i is less than n. With five records, the last index is 4. Writing less-than-or-equal would read past the end, which is undefined behavior.
Algorithm
Tracking the Champion by Index
Now the champion. The variable best holds the index of the top player so far. It starts at 0: Mira, with 4200. Jo's 3150 isn't bigger, so best stays. Kai's 5075 is, so best becomes 2. Zed's 980 and Lin's 4410 are both smaller. The loop ends with best equal to 2. Why keep an index, and not just the top score? Because the index leads back to the whole record, so the program can print the name too.
Sample Run
Total, Average, and Top Player
In the code, that's the if inside the loop: best changes only when a bigger score appears. Build and run. Five rows, a total of 17815, an average of 3563, and the top player: Kai, with 5075. The last line uses board best twice: once for the name, once for the score.
Quick Check
Copying One Element Over Another
Quick check. A short board of three. Element 2 is set equal to element 1, and then element 1 gains 50 points. What does the program print? Pause and predict. Build and run: Zed 550, then Zed 500. b 2 equals b 1 copied the whole record, name and score, so Lin's entry became a second Zed with 500. The bonus then went to element 1 only. Copies of structs are independent, even inside one array.
Sorting Idea
Swapping Whole Records With a Temporary
A leaderboard should show the best player first. Use the bubble sort from 7.8: compare neighbors, and swap them when they're in the wrong order. The comparison looks at one member, the score. But the swap moves the whole struct, so each name stays attached to its score. Take Jo and Kai, two neighbors in the wrong order. Swapping them needs a helper, just like swapping two ints. Step one saves Jo in tmp. Step two copies Kai into Jo's place. Step three copies the saved Jo into Kai's old place. Both records moved whole.
Worked Example
Bubble Sort by Score
Here's the program. The helper print_board takes the array and its length, as in 7.3. The if compares board i dot score with the next one. If the next score is bigger, the three lines swap the whole records. Build and run. Kai is first with 5075, then Lin, Mira, Jo and Zed. Every name still sits beside its own score.
Key Takeaways
Records Side by Side in Memory
To sum up. An array of structs is a row of identical records, in one block of memory. The index picks the record, and the dot picks the member: board i dot score. Loop with i less than n, and remember the best record by its index. To sort, compare one member, but swap whole structs.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Arrays of Structures in C
How do you access a member of a struct inside an array in C?
How do you count the elements in an array of structs?
Why track the index instead of the value when finding the best record?
How do you sort an array of structs by one field in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →