UPI Study › Courses › Programming in C › Free lessons › Lesson 10.5 Free with a free account
Passing and Returning Structures in Functions
Programming in C · Chapter 10: Structures, Unions, and Compound Data ModelingSection 10.5 · lesson 68 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: The Union Data Type in C →← Pointers to Structures in CNext lesson: The Union Data Type in C →
In this lesson
Passing structs by value or by address and returning them.
- Explain why a struct passed by value is copied, array members included
- Pass a struct's address when a function must change the original
- Write a function that builds and returns a whole struct
- Use a const pointer parameter for a large struct that a function only reads
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 (789 words). Read along, or search it.
Opening Question
Xira Inside, Mira Outside
Priya writes give_bonus. It adds 500 points to a player, and, just to be thorough, changes the first letter of the name. Build and run. Inside the function, the player is Xira, with 4700. Outside, she's still Mira, with 4200. One player, two different stories. Why? And when is that the behavior you actually want?
Roadmap
Into a Function and Back Out
This lesson follows a struct into a function, and back out. You'll pass a copy, then pass the address, then return a whole struct from a function. Last, you'll weigh what a copy costs, and use const to make a read-only promise.
Pass by Value
The Function Gets Its Own Copy
Here's what happened. A struct passed to a function follows the same rule as an int, from 6.5: the function gets its own copy. That's called pass by value. Every member is copied, even the letters inside the name array. So p starts as a second Mira with 4200. Then give_bonus adds 500 to p's score, and puts an X in p's name. When the function ends, its copy is thrown away. mira, back in main, never knew.
Memory Picture
Arrays Inside Structs Are Copied Too
So there were two separate boxes. mira in main still holds Mira and 4200. The copy, p, ended as Xira with 4700. Look at the name. Pass an array on its own, and only its address travels, as you saw in 7.3. But wrap the array in a struct, and the whole thing is copied, letter by letter. That's why the X never reached Mira.
Quick Check
Passing the Address Instead
Quick check. Priya changes give_bonus to take a struct Player star, and to use the arrow for both changes. The call now passes ampersand mira. What do the two lines print? Pause and predict. Build and run: Xira, with 4700, both inside and outside. Only the address traveled. So p arrow score and p arrow name zero both reach mira itself, letters included. And if you forget the arrow or the ampersand, clang stops with an error, as you saw in 10.4.
Returning Structs
A Function That Returns a Player
A function can also return a struct, the same way it returns an int. That's handy for building a filled-in record. Priya's make_player takes a name and a score, and hands back a ready-made Player. Inside, snprintf copies the name safely, as in 7.6, because a plain equals can't copy a whole array. The returned struct is copied into best. Then second equals best copies every member, the name's letters included. So changing second's score leaves best alone. Build and run: best is Kai with 5075, and second is Kai with 3150. Two independent boxes, holding the same name.
Performance
Measuring the Cost of a Copy
Copying a small struct is nothing. But how big is a struct? Ask sizeof. Here's a second struct, Profile. Besides a name, it remembers the last 50 scores. Build and run. On this Mac, a Player is 20 bytes, a Profile is 216, and a pointer is 8. So passing a Profile by value copies 216 bytes on every call. Passing its address copies just 8. For a tiny struct, that hardly matters. For a big one, called again and again in a busy loop, it can.
Rule of Thumb
Small by Value, Big by Pointer
So most C programmers follow a simple rule: small structs can go by value, and big ones go by pointer. But a pointer opens a door: the function could change the original by accident. The keyword const closes that door.
Read-Only Access
Const Pointers Block Accidental Changes
Here, show takes a const struct Player star. It says: p points at a Player that this function will only read. Now suppose show breaks that promise, and sets the score to zero. Build it. Clang refuses: cannot assign to variable p with const-qualified type. A note points back to the parameter. The wording names p, but what's protected is the Player that p points to. And the slip is caught before the program ever runs. Delete that line, and show builds and runs normally. Mira has 4200, and the original is never touched. So give read-only functions a const pointer, by habit. A reader sees at once that show can't damage a player.
Quick Check
Changing a Local Copy Is Allowed
One more check. preview_reset takes a const pointer, copies the Player into a local struct, and sets the copy's score to zero. Then main prints mira's score. What happens? Pause and predict. It builds, and prints Mira 0, then 4200. const protects the Player that p points to. Reading it is fine, and copy equals star p only reads. The copy is a separate local struct, so the function may change it freely. mira's score never moves.
Key Takeaways
Copies, Addresses, Returns, and Const
To sum up. Pass a struct by value, and the function works on its own copy. Pass its address, and changes reach the original. A function can return a whole struct, which is handy for building records. And for a big struct the function only reads, pass a const pointer.
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 Passing and Returning Structures in Functions
Does passing a struct to a function copy its array members?
Can a function return a struct in C?
When should you pass a struct by pointer instead of by value?
What does a const struct pointer parameter mean 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 →