Arrays of Structures in C, Explained with Code Examples

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

← Defining Structures in CNext lesson: Pointers to Structures in C →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Put the index first and the dot second: board[2].score reads the score of element 2, the third record. The brackets pick one whole struct from the array, and the dot picks a member inside it. Because each element is a complete struct, board[i].name and board[i].score always belong to the same record.
How do you count the elements in an array of structs?
Divide the size of the whole array by the size of one element: sizeof board / sizeof board[0]. Five 16-byte records give 80 divided by 16, which is 5. This works only where the array was declared. Inside a function that received the array as a parameter, board is just an address, so pass the length as a separate argument.
Why track the index instead of the value when finding the best record?
An index leads back to the whole record, so the program can print the winner's name as well as the score. Start best at 0, and inside the loop set best = i whenever board[i].score is bigger than board[best].score. When the loop ends, board[best].name and board[best].score describe the top player.
How do you sort an array of structs by one field in C?
Compare one member but swap whole structs. In a bubble sort, compare board[i].score with board[i + 1].score, and when they are out of order, swap the two records through a temporary: tmp = board[i]; board[i] = board[i + 1]; board[i + 1] = tmp;. Because the whole struct moves, each name stays attached to its own score.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →