Passing Array Addresses to Functions | Programming in C

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

← Arrays of Pointers in CNext lesson: Pointer-Based String Processing →

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

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.

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 Array Addresses to Functions

Is int a[] the same as int *a in a C function parameter?
Yes. In a parameter list, int a[] and int *a mean exactly the same thing: the function receives an address, because the array argument decays. Inside, a[i] works with either spelling. The brackets suggest a row of values to readers, and the star suggests an address. Either way, the function cannot learn the length from a, so pass it as a separate parameter, such as n.
How do you pass part of an array to a function in C?
Pass the address where the part begins and the number of elements to use. If sum(int *a, int n) adds n values, then sum(laps + 2, 3) adds laps[2], laps[3], and laps[4], because laps + 2 is the address of element 2. Inside the function, a[0] is the caller's laps[2], and the function knows nothing about the elements outside that window.
What does const int *a mean in a C function parameter?
const int *a means a points to ints the function may read but not change. Writing *a = 0; or a[i] = 0; gives a read-only variable is not assignable error. The pointer itself is not constant, so a++ is still allowed. Marking every pointer parameter that is only read as const lets the compiler catch accidental writes to the caller's data.
Why is returning the address of a local variable a bug in C?
A local variable lives in the function's space on the call stack, which is given back the moment the function returns, so the returned address points to a box that is gone. Using it is undefined behavior and can crash or print junk. Clang warns in simple cases but not all. Instead, return a pointer into an array the caller owns, or let the caller pass in a place to write.

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 →