UPI Study › Courses › Programming in C › Free lessons › Lesson 10.7 Free with a free account
Workshop: Modeling Real-World Entities with Structures and Unions
Programming in C · Chapter 10: Structures, Unions, and Compound Data ModelingSection 10.7 · lesson 70 of 787 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: Singly Linked List Fundamentals →← The Union Data Type in CNext lesson: Singly Linked List Fundamentals →
In this lesson
Validating struct data, tagged union makers, and a counted inventory.
- Write validation functions so a struct is filled only when every field passes
- Build maker functions that set a tagged union's tag and member together
- Manage an array of structs with a count that tracks the used slots
- Compute a report of income per record and a grand total
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 (989 words). Read along, or search it.
The Challenge
Letting Only Good Data In
A struct will hold anything, even nonsense: a machine with no name, or one that costs minus five tokens a play. The computer stores it happily. So a careful programmer builds a front door that lets only good data in. In this workshop, you'll build three small programs for the Starlight Arcade. A machine that checks its own fields, a prize that's one of three kinds, and a floor inventory with a report.
Program One Plan
Two Rules for an Arcade Machine
Program one: a machine that checks itself. struct Machine keeps a name, and the tokens one play costs. The name gets at most 15 letters, because the sixteenth box holds the null character that ends the string, as in 7.5. Two rules protect it. The name can't be empty or too long, and the cost can never be negative. Zero is fine: a free play. Each rule gets a small function that answers 1 for good, and 0 for bad. And make_machine is the front door. It fills the struct only when both answers are yes.
Program One Code
Validating Before Filling the Struct
The functions follow the plan, one for one. valid_name measures the name with string length, and accepts 1 to 15. valid_cost accepts any cost of zero or more. make_machine receives the address of the struct to fill, as in 10.5. Then it asks both questions, before it writes anything. Only then does it copy the name, with snprintf, which stops at the sixteen boxes, whatever it's handed. show_machine takes a const pointer, because it only reads. Sam's four tests: one good machine, an empty name, a name that's too long, and a negative cost. Build and run. Rocket Race gets in, at 3 tokens a play. The other three are turned away, each with its reason.
Quick Check
Sixteen Characters Is One Too Many
Quick check. Sam tests the two rules on their own. Turbo Tank Blitz has sixteen characters, Turbo Tank has ten, and the cost is zero. What three numbers does it print? Pause and predict. Build and run: 0, 1, 1. Sixteen characters is one too many: a 16-box name array needs its last box for the null character. Ten is fine. And a cost of zero passes, because only negative costs are turned away. A free play is allowed.
Program Two Plan
One Maker Function per Prize Kind
Program two: a prize that's one of three things. From 10.6, that's a tagged union: an enum tag, plus a union. The new idea is one maker function per kind, with three jobs: check the value, set the tag, and store the member. Tokens must be 1 to 1000. A toy name, 1 to 15 letters. And a discount, 1 to 90 percent. If the tag and the member are always set together, they can't get out of step. So the display function can trust the tag.
Program Two Code
Check, Set the Tag, Store the Member
Here's the code. The enum and the struct, folded here, are the ones from 10.6. make_tokens checks first. If the value is out of range, it returns 0, and leaves the prize untouched. Otherwise it sets the tag, and then the member, one right after the other. make_toy and make_discount follow the same three steps. show_prize is the switch from 10.6. It reads only the member that the tag names. In main, one variable, p, serves all three prizes. Each maker overwrites the shared spot, and the tag along with it. Build and run: 25 bonus tokens, a Robot toy, 20 percent off, and the discount of 150 is rejected.
Quick Check
A Rejected Value Leaves the Prize Intact
Quick check. First, make_toy fills p. Then make_tokens is asked for 5000 tokens. What does show_prize print? Pause and predict. It prints a Rubber Duck toy. 5000 is out of range, so make_tokens returns 0 before it touches anything. The tag and the toy name stay as they were, still in step. That's why each maker checks first, and only then sets the tag and the member.
Program Three Plan
An Array of Machines Plus a Count
Program three: the floor inventory. The arcade floor holds up to 4 machines. Priya keeps them in an array of structs, as in 10.3, plus an int called count: how many slots are in use. Slots 0 up to count minus 1 hold real machines. The rest are empty. So one number does two jobs. With two machines in, count is 2. That's how many there are, and slot 2 is where the next one goes.
Adding Machines
Checking Room and Fields Before Writing
add_machine checks for room first. If count has reached MAX, the floor is full, and nothing is written. Next it checks the fields: a name of 1 to 15 letters, and no negative tokens or plays. Only then does it fill the next free slot, list at count. And it adds 1 to count. count arrives as an int star, so star count, plus plus, changes the caller's own number. And list is really an address, as in 7.3. So the slots being filled are in the caller's real array.
Report
Income per Machine and Grand Total
report loops from 0 up to count, and works out each machine's income: tokens per play, times plays. It prints one row for each machine. After the loop, it prints the grand total, the sum of every income. main tries six machines. One has an empty name, and the sixth won't fit. Build and run. The empty name is rejected, and Air Hockey finds the floor full. Four machines made it in: 360, plus 170, plus 240, plus 200. That's 970 tokens.
Key Takeaways
Validate First, Then Fill
To sum up. Check every field first, and fill a struct only when all of them pass. Give each kind of a tagged union its own maker, which sets the tag and the member together. Keep an array of structs with a count: how many are in use, and where the next one goes. And give functions that only read a const pointer.
Try It
Three Challenges to Extend the Arcade
Three challenges to try on your own. First, add plays to machine.c, with a check that rejects negative numbers. Second, add a fourth prize kind, a free-play pass. Build before you add its case, and read clang's warning. Third, write a function that finds the busiest machine on the floor.
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 Workshop: Modeling Real-World Entities with Structures and Unions
How do you validate data before storing it in a struct in C?
How do you keep a tagged union's tag and value in sync?
How do you add records to a fixed-size array of structs in C?
How do you calculate a value for each record in an array of structs?
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 →