Passing arrays to functions
- C course
- Beginner
- Lesson 79/116
- 5 min
Learn to pass arrays to functions as pointers.
Passing arrays to functions
When you pass an array to a function the array name decays into a pointer. In the function signature you can write int arr[] or int *arr; both mean the same.
int sum(int arr[], int n) {
int total = 0;
for (int i = 0; i < n; i++) total += arr[i];
return total;
}The array length does not come with the pointer; the n parameter is passed separately. The function sees the original array, not a copy.
sizeof gives pointer size on a parameter
Inside a function sizeof(arr) does not give the array size; it gives the pointer size (usually 4 or 8 bytes). This is why you must pass the array length as a separate parameter.
void print_all(int *arr, int n) {
/* sizeof(arr) is 4 or 8 here! */
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
}This is the most common pitfall of array decay. Always carry the length separately.
Practice Write a sum function
Define int sum(int *arr, int n): with a for loop sum the array elements and return the total variable. In main define int arr[3] = {4, 5, 6}; and print the result with printf("%d\n", sum(arr, 3));. Output should be 15.
Starter code
#include <stdio.h>
/* define sum here: returns the total of an int array */
int main(void) {
int arr[3] = {4, 5, 6};
/* print the total via sum */
return 0;
}Sample solution
#include <stdio.h>
int sum(int *arr, int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}
int main(void) {
int arr[3] = {4, 5, 6};
printf("%d\n", sum(arr, 3));
return 0;
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match signatures and meanings
| Term | Meaning |
|---|---|
int arr[] |
array parameter |
int *arr |
pointer parameter |
arr, 3 |
array and size |
sum(arr, n) |
function call |
2 Which signature accepts an int array?
- void f(int[] arr)
- void f(int arr)
- void f(int *arr[])
- void f(int arr[]) Correct answer
Explanation: int arr[] accepts an int array (as a pointer).
3 Pass array and size to function
int arr[3] = {1, 2, 3};
sum(arr, ____); /* pass 3-element array */
int arr[3] = {1, 2, 3};
sum(arr, 3); /* pass 3-element array */
Explanation: A 3-element array needs size 3.