Defining Structures in C, Explained with Code Examples

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

← Workshop: Saving and Restoring Structures in Binary FilesNext lesson: Arrays of 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

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.

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 Defining Structures in C

What is a struct in C?
A struct is a type you design yourself that bundles several variables, called members, under one name. You write struct, a tag, and the members with their types inside braces, followed by a semicolon. The definition is only a blueprint and uses no memory until you declare a variable from it, such as struct Player a. Then a.score reaches one member through the dot operator.
Why does Player a; fail when struct Player is defined in C?
In C, the word struct is part of the type's name, so after defining struct Player you must declare struct Player a, not Player a. Clang reports that you must use the struct tag. To use the short name, wrap the definition in typedef, as in typedef struct { char name[16]; int score; } Player;, which lets you declare Player a directly.
What is a designated initializer in C?
A designated initializer names each member with a dot, so values can appear in any order: Player p = {.name = "Jo", .tokens = 5};. Any member you leave out is set to zero, so p.score here starts at 0, and = {0} zeros every member. Designated initializers suit large structs, because a member added later does not push values into the wrong places.
Can you copy a struct with the = operator in C?
Yes. Writing b = a copies every member of a into b, even the characters of an array member, which plain array assignment cannot do. After the copy, the two structs are independent: adding 100 to b.score leaves a.score unchanged. One caveat: a pointer member is copied as an address, so both structs then point at the same data, and a change made through that pointer shows up in both.

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 →