Pointers to Structures in C, Explained with Code Examples

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

← Arrays of Structures in CNext lesson: Passing and Returning Structures in Functions →

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

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.

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 Pointers to Structures in C

What does the arrow operator do in C?
The arrow operator follows a pointer to a struct and picks a member in one step, so p->score means the same as (*p).score. If p holds the address of hero, p->score += 50 changes hero's own score. Use the arrow on a pointer to a struct and the dot on a struct variable; clang rejects the wrong one and suggests the other.
Why does *p.score cause a compile error in C?
The dot operator binds more tightly than the star, so C reads *p.score as *(p.score). Since p is a pointer, not a struct, p.score is an error, and clang suggests using the arrow instead. Write (*p).score with the parentheses, or better, p->score, which needs no parentheses at all.
Why doesn't my function change the struct I passed to it?
C passes arguments by value, so the function receives its own copy of the struct and changes only that copy, which disappears when the function returns. To change the original, declare the parameter as a pointer, such as void award(Player *p), update p->score inside, and call it with the address: award(&hero). Passing an address is also cheaper than copying a large struct.
How do you allocate a struct with malloc in C?
Call malloc with the size of what the pointer points to: Player *p = malloc(sizeof *p);. If no memory is available, malloc returns NULL, so check before using p. Fill the members through the arrow, call free(p) when finished, and set p = NULL. Writing sizeof p without the star requests only the size of a pointer, often 8 bytes, which is too small for the struct.

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 →