Passing Arrays to Functions in C, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 7.3 Free with a free account

Passing Arrays to Functions in C

Programming in C · Chapter 7: Arrays, Strings, Input Validation, and Formatted OutputSection 7.3 · lesson 42 of 785 min · free with a free account

← Array Initialization in CNext lesson: Multi-Dimensional Arrays 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

How C hands arrays to functions by address, with size and const.

  • Explain why an array argument passes the address of its first element
  • Write a function that takes an array parameter and an element count
  • Explain why sizeof inside a function measures an address, not the array
  • Use const to mark an array parameter as read-only

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 (631 words). Read along, or search it.

Opening Question

Why Copying Five Hundred Scores Is Slow

In lesson 6.5, a function got a copy of a number, so it couldn't change the caller's variable. Now the arcade wants a function that gives a bonus to all five hundred scores. Copying five hundred boxes on every call would be slow. So when you hand C an array, it does something clever, and a little surprising. That trick explains both its power, and its biggest trap.

Base Address

The Array Name Becomes an Address

When you write just an array's name in a call, C doesn't copy the boxes. It hands over the address of the first box: where in memory the row begins. Think of giving a friend the locker number where the row starts, instead of photocopying everything inside. Your friend walks to the same lockers. That address of the first element is the base address. The compiler converts the array into it, automatically. A pointer is a variable that holds an address. You'll make your own in lesson 8.2. For now, keep the picture: one row of boxes, two ways to reach it.

Worked Example

A Function That Adds a Bonus

Here it is in code. In the parameter list, write the element type, a name, and empty square brackets. The function's loop adds ten to every box. In the call, write only the array's name, with no brackets, and no ampersand. The count goes along as a second number. Run it. Every score went up by ten: sixty, seventy, eighty, ninety. And main never assigned anything. In 6.5, a plain int arrived as a copy. This function got the address of the row, so its changes land in main's own boxes.

Common Trap

Sizeof Fails Inside the Function

An address says where the row starts, but not how long it is. So the size doesn't travel. You pass it yourself, as a separate parameter. Now the trap. In 7.1 you counted boxes with sizeof. Inside a function, that fails, because scores there is only an address. Clang knows, and warns: sizeof on array function parameter will return size of int star, instead of int array. The program still runs. In main, sizeof scores is sixteen: four boxes of four bytes. Inside the function, it's eight, the size of an address on this machine. But count says four, because we passed it. The safe habit: count where the array was declared, and pass the count along.

Quick Check

The Array Changes, the Plain Int Does Not

Quick check. A function called spend gets an array of lives, and a number n. It takes one off n, then zeroes that box. Main passes lives and its own n, which is three. What does the last line print? Pause and predict. Three, zero, three. The array came as an address, so zeroing box two inside spend changes main's own box. But n came as a plain int, a copy. Spend made its copy two, and main's n is still three. Both rules, in one call.

Read-Only Parameters

Const Promises the Function Only Reads

Sharing the real boxes is powerful, but risky if a function that should only look changes something by accident. The keyword const in front of the parameter type is a promise: I will only read these boxes. A function that adds up scores gets const. Main counts the boxes where the array lives, and passes the count. Run it: a total of two hundred sixty. Priya once typed scores of i equals zero inside a const total function. Clang refused to build it: read-only variable is not assignable. The compiler is a free tester, Sam said. Leave const off only for functions that are meant to change the boxes, like add bonus.

Key Takeaways

Address, Count, and Const

To recap. An array argument becomes the address of its first box, so the function works on the caller's own boxes. The size doesn't travel, and sizeof inside the function measures only the address. So count where the array lives, and pass the count. And const promises read only, and the compiler enforces it.

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 Arrays to Functions in C

Can a C function change the elements of an array passed to it?
Yes. When you pass an array by name, C passes the address of its first element, called the base address, instead of copying the elements. The function therefore works on the caller's own elements, so a loop that adds 10 to scores[i] inside the function changes the array in main. A plain int parameter is different: it arrives as a copy, so changing it leaves the caller's variable alone.
Why does sizeof give the wrong size for an array parameter in C?
Inside the function, an array parameter such as int scores[] is really an address, so sizeof scores gives the size of an address, not of the whole array. On a typical 64-bit machine that is 8 bytes, while sizeof scores in main for an array of four ints is 16. Clang warns about this. Count the elements where the array is declared and pass that count as a separate parameter.
How do you write a C function that takes an array as a parameter?
Write the element type, a parameter name, and empty square brackets, then add a separate parameter for the count, as in void add_bonus(int scores[], int count). In the call, use just the array's name with no brackets and no ampersand, as in add_bonus(scores, 4). The count matters because an address tells the function where the array starts but not how many elements it has.
What does const mean on an array parameter in C?
const promises that the function will only read the array's elements. In int total(const int scores[], int count), a line like scores[i] = 0; is a compile error; clang reports that a read-only variable is not assignable. Use const for functions that only look, such as summing or printing, and leave it off for functions meant to change the elements, such as one that adds a bonus.

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 →