On this page (15 sections)
- 🎯 Why Pass Arrays to Functions?
- 1️⃣ Passing a Single Element
- 2️⃣ Passing the Whole Array
- 3️⃣ The Big Difference: The Function Can Change the Original
- 4️⃣ Why the Size Must Be Passed Separately
- 5️⃣ Searching: Linear Search as a Function
- 6️⃣ Maximum and Minimum
- 7️⃣ Sorting: Bubble Sort as a Function
- 8️⃣ Reversing an Array In Place
- 9️⃣ Passing a Two-Dimensional Array
- 🔒 Protecting an Array with const
- 🧭 Quick Guide: Element or Whole Array?
- ⚠️ Common Mistakes
- ❓ Frequently Asked Questions
- ✅ Key Takeaways
Module II · Functions · Passing Arrays to Functions
🎯 Why Pass Arrays to Functions?
A teacher keeps the marks of 60 students. She wants one routine to find the total, another to find the topper and another to sort the list. Writing the same loops again and again inside main() would be messy. A far better plan is to write each job once as a function and hand it the whole list.
To work on a whole array, a function needs two things: the array itself and the number of elements in it. This lecture shows how to pass them, why the function can change the original array, and how to build small modular programs for sum, search, maximum, sorting and more.
main() owns the array 4562789055[0][1][2][3][4] |
| ⬇ array + size 5 |
arraySum(arr, n) adds the elements: sum = 330 |
| ⬇ returns 330 |
main(): total = 330 |
Figure 1: The caller hands over the array and its size. The function does the work and returns a result.
1️⃣ Passing a Single Element
Start with the simplest case. An element such as marks[1] is just an ordinary int. Passing it follows the call by value rule you learned in the previous lecture.
Program 1: Passing one array element
#include <stdio.h>
void tryToChange(int n);
int main(void) {
int marks[3] = {50, 60, 70};
tryToChange(marks[1]);
printf("marks[1] is still %d\n", marks[1]);
return 0;
}
void tryToChange(int n) {
n = 999;
printf("Inside: n = %d\n", n);
}
Inside: n = 999
marks[1] is still 60
marks[1]holds 60. The call copies that value into the formal parametern.- The function sets its copy to 999, but the array element stays 60.
- So a single element is passed by value, like any other variable.
2️⃣ Passing the Whole Array
To pass the entire array, write only its name in the call, with no brackets and no index. In the function, declare the parameter with empty square brackets.
int arraySum(int arr[], int n); /* prototype */
total = arraySum(marks, 5); /* call: name of the array and its size */
int arr[]. The size goes in a second parameter such as int n, because the function cannot find the length by itself.Program 2: Sum and average of an array
#include <stdio.h>
int arraySum(int arr[], int n);
int main(void) {
int marks[5] = {45, 62, 78, 90, 55};
int total = arraySum(marks, 5);
printf("Total = %d\n", total);
printf("Average = %.1f\n", total / 5.0);
return 0;
}
int arraySum(int arr[], int n) {
int i, sum = 0;
for (i = 0; i < n; i++) {
sum = sum + arr[i];
}
return sum;
}
Total = 330
Average = 66.0
arraySum(marks, 5)passes the array namemarksand the count 5.- The loop adds every element: 45 + 62 + 78 + 90 + 55 = 330.
- The function returns the total.
main()stores it and prints the average as 330 / 5.0 = 66.0. - The same function works for an array of any length. Just change the second argument.
3️⃣ The Big Difference: The Function Can Change the Original
Here is the surprise. A single int is copied, but an array is not. When you pass an array name, C passes the address of the first element, not a copy of all the elements. So the function works on the very same memory as main().
Program 3: A function that doubles every element
#include <stdio.h>
void doubleAll(int arr[], int n);
void printArray(int arr[], int n);
int main(void) {
int data[4] = {3, 8, 5, 10};
printf("Before: ");
printArray(data, 4);
doubleAll(data, 4);
printf("After: ");
printArray(data, 4);
return 0;
}
void doubleAll(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
arr[i] = arr[i] * 2;
}
}
void printArray(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
Before: 3 8 5 10
After: 6 16 10 20
doubleAllis avoidfunction. It returns nothing.- Yet after the call,
datainmain()holds 6, 16, 10, 20. The function changed the original array. - Compare this with Program 1, where a single element could not be changed. An array name passes where the array lives, so changes stick.
int data[4]3→68→165→1010→20arr holds the address of data[0]arr = address of data[0]Figure 2: The function receives the address of the first element, so arr[i] is the same memory as data[i].
Passing marks[1] | Passing marks | |
|---|---|---|
| What is sent | A copy of one value | The address of the first element |
| Can the function change the original? | No | Yes |
| Parameter in the function | int n | int arr[] |
| Size needed as a separate argument? | No | Yes |
4️⃣ Why the Size Must Be Passed Separately
Inside the function, arr only knows where the array starts. It has no idea where the array ends. Because of this, sizeof(arr) inside a function does not give the array size: it measures a pointer, not the array.
So main() works out the number of elements, where the array is declared, and sends it along. A handy formula is:
int n = sizeof(roll) / sizeof(roll[0]); /* total bytes / bytes of one element */
5️⃣ Searching: Linear Search as a Function
Program 4: Linear search that returns the index
#include <stdio.h>
int linearSearch(int arr[], int n, int key);
int main(void) {
int roll[6] = {101, 105, 110, 120, 125, 130};
int n = sizeof(roll) / sizeof(roll[0]);
int pos = linearSearch(roll, n, 120);
if (pos != -1)
printf("Found 120 at index %d\n", pos);
else
printf("120 not found\n");
pos = linearSearch(roll, n, 111);
if (pos != -1)
printf("Found 111 at index %d\n", pos);
else
printf("111 not found\n");
return 0;
}
int linearSearch(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key)
return i;
}
return -1;
}
Found 120 at index 3
111 not found
main()calculatesnwithsizeofand passes the array, its size and the key.- The loop checks each element. On a match,
return i;leaves the function at once with the index. - If the loop finishes with no match, the function returns -1, a value that can never be a real index.
main()tests the result: -1 means “not found”.
Trace for key = 120:
| i | arr[i] | arr[i] == 120 ? | Action |
|---|---|---|---|
| 0 | 101 | No | Continue |
| 1 | 105 | No | Continue |
| 2 | 110 | No | Continue |
| 3 | 120 | Yes | return 3; |
6️⃣ Maximum and Minimum
Program 5: Highest and lowest temperature
#include <stdio.h>
int findMax(int arr[], int n);
int findMin(int arr[], int n);
int main(void) {
int temp[7] = {31, 28, 35, 22, 40, 29, 33};
printf("Highest = %d\n", findMax(temp, 7));
printf("Lowest = %d\n", findMin(temp, 7));
return 0;
}
int findMax(int arr[], int n) {
int i, max = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
int findMin(int arr[], int n) {
int i, min = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] < min)
min = arr[i];
}
return min;
}
Highest = 40
Lowest = 22
- Both functions start by assuming the first element,
arr[0], is the answer. - The loop starts at index 1 and replaces the answer whenever a better element appears.
- Neither function changes the array. They only read it and return one value.
7️⃣ Sorting: Bubble Sort as a Function
Sorting is the perfect example of why a function must be able to change the original array. The sort rearranges the elements in place, and main() sees the sorted list afterwards, with nothing returned.
Program 6: Bubble sort and a print helper
#include <stdio.h>
void bubbleSort(int arr[], int n);
void printArray(int arr[], int n);
int main(void) {
int a[6] = {64, 25, 12, 22, 11, 90};
printf("Unsorted: ");
printArray(a, 6);
bubbleSort(a, 6);
printf("Sorted: ");
printArray(a, 6);
return 0;
}
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
Unsorted: 64 25 12 22 11 90
Sorted: 11 12 22 25 64 90
- Each pass of the outer loop compares neighbours and swaps them if they are in the wrong order. The largest remaining element “bubbles” to the end.
j < n - 1 - istops each pass earlier, because the lastielements are already in place.- The swap works here because it swaps array elements through the array’s address. It is not a swap of copies, like the one that failed in the last lecture.
printArrayis a small helper reused before and after sorting. This is the modular style.
Trace of the first pass on {64, 25, 12, 22, 11, 90}:
| j | Compare | Swap? | Array after the step |
|---|---|---|---|
| 0 | 64 > 25 | Yes | 25 64 12 22 11 90 |
| 1 | 64 > 12 | Yes | 25 12 64 22 11 90 |
| 2 | 64 > 22 | Yes | 25 12 22 64 11 90 |
| 3 | 64 > 11 | Yes | 25 12 22 11 64 90 |
| 4 | 64 > 90 | No | 25 12 22 11 64 90 |
642512221190251222116490122211256490121122256490111222256490111222256490Figure 3: Green boxes are in their final place after each pass. Blue boxes are still being compared.
8️⃣ Reversing an Array In Place
Program 7: Reverse an array
#include <stdio.h>
void reverseArray(int arr[], int n);
void printArray(int arr[], int n);
int main(void) {
int a[5] = {1, 2, 3, 4, 5};
reverseArray(a, 5);
printArray(a, 5);
return 0;
}
void reverseArray(int arr[], int n) {
int i, temp;
for (i = 0; i < n / 2; i++) {
temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
}
void printArray(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
5 4 3 2 1
- The loop runs only
n / 2times. Each round swaps the element at positioniwith its mirror atn - 1 - i. - For 5 elements, the pairs are (0, 4) and (1, 3). The middle element, index 2, stays where it is.
- Running the loop all the way to
nwould swap every pair twice and undo the reversal. That is a classic mistake.
9️⃣ Passing a Two-Dimensional Array
A 2-D array can be passed too, but there is one extra rule. The function must be told the number of columns in the parameter declaration. The number of rows can be left out and passed separately.
Program 8: Sum of all elements of a matrix
#include <stdio.h>
int matrixSum(int m[][3], int rows);
int main(void) {
int table[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("Sum of all elements = %d\n", matrixSum(table, 2));
return 0;
}
int matrixSum(int m[][3], int rows) {
int i, j, sum = 0;
for (i = 0; i < rows; i++) {
for (j = 0; j < 3; j++) {
sum = sum + m[i][j];
}
}
return sum;
}
Sum of all elements = 21
int m[][3]says: an array of rows, where each row has exactly 3 integers.- The number of rows (2) is passed as the second argument.
- The nested loops visit every element: 1+2+3+4+5+6 = 21.
123456That is why
[3] (the column count) is required.Figure 4: A 2-D array is laid out row by row, so the function needs the column count to find each element.
🔒 Protecting an Array with const
Some functions only need to read an array, such as one that counts or searches. Adding the word const to the parameter tells the compiler, and the reader, that the function must not change the elements.
Program 9: A read-only function using const
#include <stdio.h>
int countAbove(const int arr[], int n, int limit);
int main(void) {
int marks[6] = {35, 72, 48, 90, 66, 81};
printf("Students above 60: %d\n", countAbove(marks, 6, 60));
return 0;
}
int countAbove(const int arr[], int n, int limit) {
int i, count = 0;
for (i = 0; i < n; i++) {
if (arr[i] > limit)
count++;
}
return count;
}
Students above 60: 4
const int arr[]means the elements are read-only inside this function.- If you wrote
arr[i] = 0;inside it, the compiler would report an error and stop you from damaging the data by accident. - Use
constfor every function that does not need to modify its array. It is good, safe practice.
🧭 Quick Guide: Element or Whole Array?
One element ➜ f(marks[1])by value cannot change the original | Whole array ➜ f(marks, n)by address can change the original pass the size too |
Figure 5: Choose between passing one element and passing the whole array.
⚠️ Common Mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Calling arraySum(marks[], 5) or arraySum(marks[5], 5) | Brackets in the call mean an element or a syntax error | Write only the name: arraySum(marks, 5) |
Using sizeof(arr) inside the function to get the length | It measures a pointer, not the array | Pass the size from main() |
| Passing the wrong size | The loop reads or writes outside the array | Pass the exact element count |
Expecting an array to be copied like an int | The function gets the address, not a copy | Remember that changes affect the original |
Looping to n in a reverse function | Every pair is swapped twice | Loop only n / 2 times |
| Leaving out the column count for a 2-D parameter | C cannot locate elements without it | int m[][3] |
Forgetting const on a read-only function | It could change data by accident | Add const |
❓ Frequently Asked Questions
Q1. Is an array passed by value or by reference?
C always passes by value, but the value of an array name is the address of its first element. That gives the effect of “by reference”: the function sees the original data.
Q2. Can a function return an array?
Not directly. A function can fill an array that main() passes in, as the examples above did. Returning arrays properly needs pointers, which come in the next lectures.
Q3. Is int arr[] the same as int *arr?
As a function parameter, yes. Both mean “the address of an int“. You will see the pointer form soon.
Q4. What if I want a function to work on a copy of the array?
Make a copy yourself first, with a loop, and pass the copy. Or use const to make sure the original is not changed.
✅ Key Takeaways
- Passing one element, such as
marks[1], is call by value: only a copy is sent. - Passing a whole array sends only its name, which stands for the address of the first element.
- The function can therefore change the original array.
- Declare the parameter as
int arr[]and pass the size as a separate parameter. - Searching, summing, finding the maximum, sorting and reversing are natural array functions.
- For 2-D arrays, the column count must appear in the parameter:
int m[][3]. - Use
conston array parameters that must stay unchanged.
🎓 Practice questions: (1) Writefloat average(int arr[], int n)and test it on five marks. (2) Write a function that counts how many even numbers an array contains. (3) Writevoid copyArray(int from[], int to[], int n)and show that the second array becomes a copy. (4) ChangelinearSearchso it returns how many times the key appears. (5) Write a function that sorts an array in descending order and print the array before and after.
All 29 lessons in this series (open course page)
Part 1 · Getting Started
- Lesson 1: Introduction to C Programming: Overview, Features and Applications
- Lesson 2: The Structure of a C Program: Building Your First Blueprint
- Lesson 3: Identifiers, Keywords and Variables: Naming Things in C Programming
- Lesson 4: Introduction to Algorithms: Thinking Before You Code
- Lesson 5: Introduction to Flowcharts: Drawing the Logic You Already Know
Part 2 · Data Types, Input/Output and Operators
- Lesson 6: Data Types in C: Choosing the Right Box for Every Value
- Lesson 7: Formatted Input and Output in C: Taking Control of printf and scanf
- Lesson 8: Practice Exercise Sheet: Data Types in C
- Lesson 9: Operators and Expressions in C: Assignment, Unary, and Arithmetic
- Lesson 10: Relational, Logical, and Conditional Operators in C
- Lesson 11: Bitwise and Special Operators in C
- Lesson 12: Operator Precedence and Associativity in C
Part 3 · Decisions and Loops
- Lesson 13: Decision and Case Control: if and if-else in C
- Lesson 14: The switch Statement — and switch vs. if-else Ladder
- Lesson 15: The for Loop: Definite Repetition in C
- Lesson 16: while and do-while Loops: Indefinite Repetition in C
- Lesson 17: break and continue in C: Controlling a Loop from the Inside
- Lesson 18: The goto Statement in C: Jumping Around Your Program
Part 4 · Arrays
- Lesson 19: 1-D Arrays in C: Declaration, Address Calculation, Insertion and Deletion
- Lesson 20: Two-Dimensional Arrays in C: Declaration, Initialization and Accessing Elements
- Lesson 21: Matrix Addition and Matrix Multiplication in C
Part 5 · Strings
- Lesson 22: Strings in C: Working with Character Arrays
- Lesson 23: 1-D and 2-D Character Arrays in C: Storing Names and Words
Part 6 · Functions and Scope
- Lesson 24: Functions in C: Declaration and Definition
- Lesson 25: Categories of Functions in C
- Lesson 26: Scope of Variables in C
- Lesson 27: Call by Value in C: How Parameter Passing Works
- Lesson 28: Passing Arrays to Functions in C: Search, Sum and Sort