UPI Study › Courses › Programming in C › Free lessons › Lesson 10.2 Free with a free account
Defining Structures in C
Programming in C · Chapter 10: Structures, Unions, and Compound Data ModelingSection 10.2 · lesson 65 of 786 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: Arrays of Structures in C →← Workshop: Saving and Restoring Structures in Binary FilesNext lesson: Arrays of Structures in C →
In this lesson
Bundling related variables into one struct type with members.
- Define a struct type and reach its members with the dot operator
- Explain why struct assignment makes an independent copy
- Initialize structs with positional and designated initializers and shorten names with typedef
- Nest one struct inside another and use sizeof to find a struct's real size
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 (837 words). Read along, or search it.
Opening Question
Three Variables That Belong Together
A player at the Starlight Arcade is more than one number. There's a name, a score, and a pile of tokens, and they all belong together. So far, that means three separate variables for every player. With fifty players, it's a hundred and fifty, and nothing says which ones go together. C lets you bundle them into one thing, with a name of your own. That bundle is called a struct.
Definition
A Blueprint of Named Members
A structure, or struct, is a type you design yourself. Write struct, a tag name, then the members, each with its own type. This list is a blueprint. Writing it uses no memory at all. Memory is used when you make a variable from it, like a, here. Notice the semicolon after the closing brace. It's required: leave it out, and clang stops with, expected semicolon after struct. To reach one member, write the variable, a dot, and the member name. The dot is the member access operator. The name is an array, so strcpy fills it. Then a dot score gets 4200, and a dot tokens gets 12.
Struct Assignment
One Assignment Copies Every Member
Now something arrays can't do. b equals a copies every member in one step, even the letters of the name. Then b's score goes up by 100. Build and run. a still has 4200. b has 4300. After the copy, the two variables are independent: changing b never touches a.
Common Mistakes
Missing Struct Tag and Assigning a Name
Two mistakes catch almost everyone. First, writing just Player a. In C, the word struct is part of the type's name. Second, filling the name with equals. An array can't be assigned, not even inside a struct. Build it. Clang reports both: must use the struct tag to refer to type Player, and array type char 16 is not assignable. The fixes are struct Player a, and strcpy for the name. Or give the type a shorter name, which is next.
Initializers
Typedef and Designated Initializers
typedef gives an existing type a new name. Wrapped around the struct, it lets you write plain Player instead of struct Player. This form, with no tag after struct, is the one most programs use for short types, and the lessons ahead use it too. You can also fill a struct as you create it. A positional initializer lists the values in the order the members were declared. A designated initializer names each member with a dot, so the order doesn't matter, and you can skip members. Any member you skip is set to zero. And brace zero sets everything to zero. Run it. Jo's score was skipped, so it's 0. And p3's empty name prints as nothing between the brackets. A tip: prefer designated initializers for big structs. If someone adds a member in the middle later, they still put each value in the right place.
Quick Check
A Copy Is Never a Link
Quick check. a starts with only its score set, to 900. b is made as a copy of a, and then gets 4 tokens. After that, a's score goes up by 1. What are the four numbers it prints? Pause and predict. Build and run: 901, 0, 900, 4. a's tokens were never named in its initializer, so they're 0. b got its own copy of every member, so its score stays 900 when a's changes. And b's 4 tokens belong to b alone. The tempting answer shares changes between them, but a copy is never a link.
Nested Structs
A Point Inside a Machine
A member can itself be a struct. Each machine in the arcade has a spot on the floor, which is two numbers, so that gets its own Point type. Then Machine uses a Point as one of its members, called pos. The initializer nests too: inner braces fill the inner struct, with x 3 and y 7. To reach the pieces inside, chain the dots. m dot pos dot x: the machine, then its position, then x. Each dot steps one level inward. Add 1 to x, and run: Pinball at 4, 7, costs 2.
Memory Layout
Member Order Changes the Size
How big is a struct? Add up the members, and you might expect the answer. But the compiler can insert padding, which you met in 10.1. Here are two structs with the same three members, in a different order. Both add up to 6 bytes: a char, an int, and a char. Run it on this Mac. Loose takes 12 bytes, and Tight only 8. In Loose, the int must start at byte 4, so three spare bytes follow a. And the struct must end on a multiple of 4, so three more follow c. Put the int first, and only two spare bytes remain, at the end. So never add the members up yourself: ask sizeof. And another compiler or machine may give different numbers.
Key Takeaways
Members, Copies, Initializers, and Sizes
To sum up. A struct is a blueprint of members, and the dot reaches one member of a variable. Assigning one struct to another copies every member, and the copies are independent. Initializers can go in order or by name, and typedef gives the type a short name. Structs can nest, and sizeof tells you the real size, padding included.
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 Defining Structures in C
What is a struct in C?
Why does Player a; fail when struct Player is defined in C?
What is a designated initializer in C?
Can you copy a struct with the = operator 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 →