Passing and Returning Structures in Functions, Explained

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

← Pointers to Structures in CNext lesson: The Union Data Type 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

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.

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 Passing and Returning Structures in Functions

Does passing a struct to a function copy its array members?
Yes. Passed by value, a struct is copied member by member, including every character of an array member such as a name. An array passed on its own sends only its address, but an array wrapped in a struct travels as a full copy. So changing p.name[0] inside the function leaves the caller's struct exactly as it was.
Can a function return a struct in C?
Yes, a function can return a struct just as it returns an int, and the caller receives a copy. A maker function such as Player make_player(const char *name, int score) can fill a local struct, copying the name with snprintf because = cannot copy an array, and then return it. Writing best = make_player("Kai", 5075); stores an independent, filled-in record.
When should you pass a struct by pointer instead of by value?
A common rule is that small structs can go by value and large ones by pointer. Passing by value copies every byte on each call: a struct holding a name and 50 ints took 216 bytes on one Mac, while a pointer took only 8. For a big struct passed often, such as inside a busy loop, passing the address avoids that copying.
What does a const struct pointer parameter mean in C?
A parameter such as const struct Player *p promises that the function will only read the Player that p points to. If the function tries p->score = 0, the compiler refuses to build it. Reading is still fine, and so is copying *p into a separate local struct, which the function may then change freely. It also tells readers the function cannot damage the caller's data.

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 →