UPI Study › Courses › Programming in C › Free lessons › Lesson 8.6 Free with a free account
Passing Array Addresses to Functions
Programming in C · Chapter 8: Pointers, Pointer Arithmetic, and String Manipulation via PointersSection 8.6 · lesson 53 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: Pointer-Based String Processing →← Arrays of Pointers in CNext lesson: Pointer-Based String Processing →
In this lesson
Array parameters as addresses, lengths, const, and safely returned pointers.
- Explain why int a[] and int *a declare the same parameter
- Pass a starting address and a length to work on part of an array
- Use const int * to promise that a function will only read
- Return a pointer into the caller's array instead of to a local variable
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 (1,038 words). Read along, or search it.
Opening Question
A Function Never Sees an Array
In seven point three, you handed an array to a function, and it just worked. Now you know the secret: the function never saw an array at all. Only an address. That one fact explains three things. How a function can total just the middle of a row, and why it must be told the length. And why it must never hand back the address of its own variable.
Two Spellings
Brackets and Star Mean the Same Parameter
When you call give bonus with scores, the array name decays, so the function receives an address, whatever you write in its parameter list. C accepts two spellings, and they mean exactly the same thing: int a with empty brackets, and int star a. Inside, a of i works either way. Use the brackets when you want readers to think, a row. Use the star when you want them to think, an address. Total a and total b are really the same function, one in each spelling. And look at the last call. The address doesn't have to be box zero. Scores plus one is the address of box one, so the function sees a row that starts there, two boxes long. Build and run. Three hundred, twice. And after the bonus, the middle boxes hold seventy and eighty, so the last total is one fifty.
The Window
A Function Sees Only From Its Start
Picture what that last call sees. The function gets the address of box one, and the number two. So its a of zero is the caller's box one, and its a of one is box two. That window is all it knows about the row. An address says where a row starts, not where it ends. So the length never travels with it.
Passing the Length
Address First, Length Right After
So here's the rule. Always pass the length as its own parameter, like n. If the function guesses, or the number is too big, the loop reads or writes outside the row. That's undefined behavior. And remember the trap from seven point three. Inside a function, sizeof a measures the address, eight bytes here, not the row. Clang even warns about it. So count the boxes where the array is declared, and pass that number along. Put the address first and the length right after it, as C's own library does.
Quick Check
Summing From Laps Plus Two
Quick check. Six lap times, and a sum function that takes an address and a length. Main passes laps plus two, and three. What does it print? Pause and predict. It prints 60. Laps plus two is the address of box two, which holds fifteen. With a length of three, the function adds fifteen, twenty and twenty-five. Forty-five would start at box one. But plus two means two boxes past the start, and inside the function, a of zero is that box.
Read-Only Pointers
Const Protects the Boxes, Not the Pointer
Passing an address gives the function the power to change the caller's boxes. Give bonus wanted that. The totals don't. You promise read only with const in front of the type. Const int star a means: a points at ints I may read, but never change. Notice what's constant: the boxes, not the pointer. So a plus plus is still allowed. Break the promise, and clang stops you: read-only variable is not assignable. The line with a plus plus gets no complaint. A good rule: every parameter that's only read gets const.
Story Resolved
The Compiler Catches a Stray Write
Back at the arcade, Sam asked Priya for a function that prints the high-score board. Priya marked its parameter const int star. Later, while testing, she typed a stray star a equals zero by accident. The compiler caught it at once. Free tester, she said, and fixed it. Sam grinned: I get to keep my job anyway.
Returning a Pointer
The Address of the Biggest Box
A function can also return a pointer, and that's useful. Largest hands back the address of the biggest box in the caller's own row. It keeps a pointer, best, and moves it whenever a bigger score turns up. The row belongs to main, so it's still there after the function ends. Main can read through the pointer, or even write through it. Build and run. The top score is ninety-five. Then star top equals one hundred changes the real box: scores of one is now one hundred.
Dangling Pointer
Returning the Address of a Local
The dangerous version returns the address of a local variable, one that belongs to the function itself. A local lives in the function's own space on the call stack, and that space is given back the moment the function returns. The address now points at a box that's gone. Using it is undefined behavior. It can crash, or print junk. Clang spots this one: address of stack memory associated with local variable bonus returned. But the program still builds and runs. That's the trap. This run never reads through p, so nothing goes wrong on screen. Whether the real bug crashes is luck.
Common Trap
A Missing Warning Is Not a Guarantee
And the warning isn't a guarantee. Store the address in a pointer first, and return that instead. Build again. Not a word from clang, though the bug is exactly the same. So treat every warning as a bug to fix now, and don't count on getting one.
Safe Choices
Three Safe Ways to Hand Back Data
So what are the safe choices? Return a pointer into an array the caller owns, as largest does. Or let the caller pass in a place to write, like scanf does. Or, in chapter eleven, reserve memory that survives the call.
Quick Check
Which Returned Pointer Is Safe
Quick check. Three functions, and each returns an int pointer. Which one returns a pointer that's safe to use after it returns? Pause and decide. Only last is safe. It returns the address of a box in the caller's own array, which outlives the call. Copy first copies the value into a local, x, and returns the address of x. That box is gone at the return. Fresh returns its own local array's name, which decays to the same kind of doomed address. Build it, and clang warns about both. The run prints ten, the last score, read safely through last.
Key Takeaways
Address, Length, Const, and Ownership
To recap. int star a and int a with empty brackets are the same parameter: an address. Pass the length with it, and you can pass any starting address, like scores plus one. Const int star promises the function won't change the boxes. And never return the address of a local. Return a pointer into the caller's array instead.
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 Array Addresses to Functions
Is int a[] the same as int *a in a C function parameter?
How do you pass part of an array to a function in C?
What does const int *a mean in a C function parameter?
Why is returning the address of a local variable a bug 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 →