UPI Study › Courses › Programming in C › Free lessons › Lesson 10.4 Free with a free account
Pointers to Structures in C
Programming in C · Chapter 10: Structures, Unions, and Compound Data ModelingSection 10.4 · lesson 67 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: Passing and Returning Structures in Functions →← Arrays of Structures in CNext lesson: Passing and Returning Structures in Functions →
In this lesson
Reaching struct members through pointers with the arrow operator.
- Use the arrow operator and explain why p->score means (*p).score
- Choose the dot or the arrow depending on whether a name is a struct or a pointer
- Pass a struct's address so a function can change the original
- Allocate a struct with malloc, check for NULL, free it, and clear the pointer
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 (996 words). Read along, or search it.
Opening Question
The Bonus That Disappeared
Sam is testing the Starlight Arcade software. He gives Mira a 500-point bonus, then prints her score. Build and run. Mira has 4200, the same as before, and the build gave no warning at all. So where did those points go? By the end of this video, you'll know, and you'll fix it.
Big Picture
A Photocopy Versus the Real Card
Think of mailing a friend a photocopy of your high-score card. They can scribble on the copy all day, and your card stays the same. To change the real card, you hand over the card itself, or tell them where it is. In C, that's the difference between passing a struct, and passing a pointer to it. So first, you'll point at a struct and reach its members with an arrow. Then you'll borrow room for a brand-new struct, from the heap.
Core Idea
Three Ways to Reach One Member
Here's one struct, hero: a Player holding Mira and 4200 points. A pointer to a struct works like any pointer from 8.2. Ampersand hero is the address of the whole struct. And p, declared as a Player star, holds that address. Now p points at hero. There are three ways to read the score. First, hero dot score, straight from the struct. Second, star p in parentheses, then dot score. Star p follows the pointer to hero, and the dot picks the member. The parentheses matter, because the dot binds tighter than the star. You'll see why in a moment. Third, the shortcut: p arrow score. The arrow follows the pointer and picks the member, in one step.
Sample Run
Changing a Struct Through Its Pointer
Build and run. All three print 4200, because they're three ways to reach one box. Now change the score through the pointer: p arrow score, plus equals 50. Then print hero itself. Build and run again. hero now holds 4250. The change went through p, and landed in hero.
Common Mistake
Why the Parentheses Matter
Now drop the parentheses around star p, and build. Two errors. The dot binds tighter, so C reads this as star applied to p dot score. And p is a pointer, not a struct. Clang says: member reference type Player star is a pointer; did you mean to use arrow? Then: indirection requires pointer operand. So keep the parentheses. Or better, use the arrow, which needs none.
Opposite Slip
An Arrow on a Plain Struct
Now the opposite slip: an arrow on hero, which is a plain struct, not a pointer. Build. Clang says: member reference type Player is not a pointer; did you mean to use dot? Both slips stop the build, and the fix is one question: is this a struct, or the address of one? A struct variable takes the dot. A pointer to a struct takes the arrow.
Quick Check
Pointer Versus Copy After Changes
Quick check. Jo starts with 3150 points in a. Then b is made as a copy of a, and p points at a. p arrow score gains 100, and b dot score gains 1. What does the program print? Pause and predict. Build and run: 3250, then 3151. p holds the address of a, so the hundred went into a itself. b was copied from a before that, so it's a separate struct. Only its own plus one shows, not the hundred.
Bug Fix
Passing an Address to Keep the Bonus
Back to Sam's bug. C passes arguments by value, as you saw in 6.5. So award gets its own copy of hero, every member. It adds 500 to that copy. Then the function ends, and the copy is gone. That's the photocopy. Priya's fix: make the parameter a Player star, and reach the score through it with the arrow. Build it. Clang stops: passing Player to parameter of incompatible type Player star. Take the address with ampersand. So add the ampersand at the call. Now award gets the address of hero, not a copy. Build and run. Mira has 4700. The bonus finally reached the real struct. Passing an address is also cheaper than copying a big struct. You'll measure that in 10.5.
Heap Allocation
A New Struct While the Program Runs
So far, every struct had a name in the code, like hero or board. But sometimes you need a new one while the program runs. Say a new player just walked up to the machine. For that, ask for room with malloc, from stdlib dot h. malloc takes a number of bytes, and returns the address of that room. And sizeof star p is the size of whatever p points to: one Player. If the struct grows later, the size stays right. If no room is left, malloc returns NULL. So check for NULL before you touch the pointer. Then fill the new Player through the arrow: string copy for the name, and 5075 for the score.
Cleanup
Free It, Then Set It to NULL
Print the result, then clean up. Call free once when you're done: it gives the room back. Then set p to NULL, so the old address can never be used by accident. Build and run. Kai has 5075 points, in 16 bytes. Where do those bytes live? The pointer p is a local variable, on the stack. The Player it points to sits on the heap. The heap is a big pool of memory. What you borrow there stays yours until you give it back. The full rules for malloc, calloc, realloc and free come in 11.2 and 11.3.
Quick Check
Size of a Pointer Versus Its Struct
One more check. This program prints two sizes on this Mac: sizeof p, then sizeof star p. Which two numbers does it print? Pause and predict. Build and run: 8, then 16. p is a pointer. On this Mac a pointer takes 8 bytes, whatever it points to. Star p is the Player itself: 16 bytes. So malloc of sizeof p, without the star, asks for only 8 bytes. Writing a whole Player there would be undefined behavior.
Key Takeaways
Dot for Structs, Arrow for Pointers
To sum up. p arrow member is short for star p, in parentheses, dot member. Use the dot on a struct, and the arrow on a pointer to one. Pass a struct's address when a function must change the original. And for a struct made while the program runs: malloc, check for NULL, free it, then set the pointer to NULL.
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 Pointers to Structures in C
What does the arrow operator do in C?
Why does *p.score cause a compile error in C?
Why doesn't my function change the struct I passed to it?
How do you allocate a struct with malloc 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 →