🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Passing Arrays to Functions
Learn how C hands an array to a function, why the callee can change your data, and how to stay in control. A beginner-friendly free C tutorial built for embedded C programming.
Passing arrays to functions in C is something every firmware developer does the moment a project grows past a single file: an ADC driver fills a buffer, a filter smooths it, a logger prints it. This lecture of our free C programming course explains exactly what happens to an array when you hand it to a function, why the called function is able to modify your original data, and how to keep that power under control. Whether you are following this free C tutorial for exams or for C programming for embedded systems, you will leave with a mental model you can trust.
What You Will Learn
- How a plain variable is copied into a function while an array is shared by address
- What array decay is, and why
int val[10]andint *valmean the same thing in a parameter list - How to write functions that modify a caller’s buffer in place
- How to protect read-only data with
const - The classic mistakes that corrupt memory on microcontrollers, and how to avoid them
Prerequisites
- Declaring, initializing and looping over one-dimensional arrays (earlier lectures of this chapter)
- Writing functions with parameters and prototypes (Functions chapter)
- A working GCC installation on Linux, macOS or WSL
Passing Arrays to Functions in C: Value vs Address
When you call f(x) with an ordinary variable, C evaluates x and places a copy of the result into the function’s parameter. The function can scribble on that copy as much as it likes and the caller’s variable never notices. That is why a helper that adds 100 to its argument cannot change the original.
Arrays look different at first glance, because a function that receives an array can clearly change the caller’s elements. Interestingly, the call mechanism itself has not changed: C is still strictly pass by value. What changed is the value being passed. In most expressions, the name of an array turns into the address of its first element. So the function receives a copy of an address, and both addresses point at the very same storage in RAM. Sharing the address means sharing the data.
What the Compiler Really Passes
Inside a parameter list, C quietly rewrites any array declaration into a pointer declaration. The number you type between the brackets is ignored, so all four forms below describe exactly the same function parameter.
| What you write | What the compiler treats it as | Comment |
|---|---|---|
void f(int v[10]) | void f(int *v) | The 10 is documentation only |
void f(int v[]) | void f(int *v) | Preferred array style, reads clearly |
void f(int *v) | void f(int *v) | Pointer style, same meaning |
call f(arr) | call f(&arr[0]) | Name decays to first-element address |
Decay has exceptions
The name-to-address conversion does not happen when the array is the operand of sizeof or of the unary & operator. That is why sizeof behaves differently inside a function, a trap we dissect in the next lecture.
Modern C note: Old textbooks write function definitions with no return type and an empty main(). Implicit int was removed from the language in C99, so current compilers warn or fail. Always write a return type, and use int main(void).
Free C Tutorial: Passing Arrays to Functions in Action
The program below plays out a realistic firmware scenario. A 12-bit ADC idles around 2048 (mid-scale), and we want a function that removes that DC offset in place so a later filter sees a signal centred on zero. We also show a scalar call that fails to change its argument, so you can compare the two behaviours side by side.
#include <stdio.h>
#include <stdint.h>
static const int16_t *last_seen;
static void bump_scalar(int level)
{
level += 100; /* changes only the local copy */
}
static void remove_dc_offset(int16_t samples[], int count, int16_t offset)
{
last_seen = samples; /* remember which address arrived */
for (int i = 0; i < count; i++) {
samples[i] = (int16_t)(samples[i] - offset);
}
}
static void show(const char *tag, const int16_t samples[], int count)
{
printf("%s:", tag);
for (int i = 0; i < count; i++) {
printf(" %d", samples[i]);
}
printf("\n");
}
int main(void)
{
int level = 7;
int16_t adc[5] = {2048, 2051, 2046, 2050, 2049};
bump_scalar(level);
printf("level after bump_scalar : %d\n", level);
show("adc before", adc, 5);
remove_dc_offset(adc, 5, 2048);
show("adc after ", adc, 5);
printf("callee saw same address : %s\n", last_seen == adc ? "yes" : "no");
return 0;
}
Save it as pass_array.c, then compile and run it:
gcc -std=c17 -Wall -Wextra -Wpedantic -o pass_array pass_array.c
./pass_array
Expected output:
level after bump_scalar : 7
adc before: 2048 2051 2046 2050 2049
adc after : 0 3 -2 2 1
callee saw same address : yes
Line-by-Line Walkthrough
- bump_scalar receives a copy of
level. Adding 100 changes the copy only, somainstill prints 7. - remove_dc_offset receives the address of
adc[0]. Every assignment tosamples[i]lands directly in the caller’s array. - last_seen is a debugging trick: we store the received address and compare it with
adcafterwards. The answeryesproves no copy of the array was made. - The numbers 2048, 2051, 2046, 2050, 2049 become 0, 3, -2, 2, 1 because each sample has 2048 subtracted.
- show only reads, so its parameter is declared
const, which leads us to the next section.
Protecting Data When Passing Arrays to Functions
Because a function can overwrite your buffer, a function that merely inspects it should promise not to. Writing const int16_t samples[] turns the parameter into a pointer to read-only elements. The caller’s array does not have to be const; the promise only restricts the callee. If the function tries to break it, the compiler stops you:
static void clear_first(const int16_t samples[])
{
samples[0] = 0;
}
error: assignment of read-only location '*samples'
Passing Arrays to Functions in Embedded C Programming
If you plan to master embedded C programming, you will write array-taking functions every week. The table shows the most common situations and the parameter style each one wants.
| Use case | Parameter style | Why |
|---|---|---|
| ADC sample buffer being filtered | int16_t buf[], size_t n | Filter updates samples in place, no extra RAM |
| UART receive buffer being parsed | const uint8_t buf[], size_t n | Parser only reads, driver owns the bytes |
| Calibration table stored in flash | const uint16_t table[], size_t n | Read-only data can live in flash, saving RAM |
| Display line buffer being drawn into | uint8_t line[], size_t n | Drawing code writes pixels straight into the buffer |
| Packet checksum calculation | const uint8_t data[], size_t len | Works on any frame size |
Common Mistakes and Troubleshooting
These are the errors beginners make most often when passing arrays to functions in C, together with the symptom you will see and the fix.
| Mistake | Symptom | Fix |
|---|---|---|
| Expecting the function to work on a copy | Original data changes “mysteriously” | Copy first with memcpy if you need the original |
| Trusting the size written in the parameter | Passing a shorter array compiles silently, then memory is overwritten | Always pass the element count as a separate argument |
Forgetting const on read-only functions | Accidental writes go unnoticed | Mark input-only parameters const |
| Copying old textbook code with no return type | Warnings or errors on modern GCC | Add return types and (void) parameter lists |
Casting away const to write | Hard fault when the data sits in flash | Never cast away const; copy to RAM first |
Best Practices, Performance and Security
Best Practices
Follow these habits every time you are passing arrays to functions in C:
- Pair every array parameter with a length, using
size_tfor the count. - Prefer the
type name[]form so readers see an array, not a lone pointer. - Use
conston every input-only array parameter. - Write a one-line comment stating whether the function modifies the array.
Performance Considerations
Passing arrays to functions by address costs the same four or eight bytes whether the array holds 5 samples or 5000. That matters on a small Cortex-M where stack space is tight. Be aware of one exception: an array wrapped inside a struct is copied in full when the struct is passed by value, so pass such structs by pointer.
Security Considerations
Most buffer overflow vulnerabilities start with a function that trusts a length it was never given. Validate the count against the real buffer capacity before writing, especially for data arriving from UART, USB, Bluetooth or the network.
Summary and Key Takeaways
Remember these points
- C always passes by value, but an array name’s value is the address of its first element.
- The callee works on the caller’s real data, so changes persist.
int v[10],int v[]andint *vare identical in a parameter list.- Pass the length separately and mark input-only arrays
const.
Understanding that arrays travel as addresses when passing arrays to functions in C removes a whole category of confusion from your first C projects. You now know why a filter can clean a buffer without copying it, why a length argument is non-negotiable, and how const documents intent while letting the compiler catch mistakes. In the next lecture of this free embedded C course we build general-purpose functions that handle arrays of any size.
Frequently Asked Questions
Is C pass by value or pass by reference for arrays?
C is always pass by value. For arrays, the value passed is the address of the first element, which gives the same practical effect as pass by reference.
Why does the size in int val[10] not matter in a function parameter?
The compiler rewrites the parameter as int *val, so the 10 is discarded. Pass the length as a separate argument.
How do I stop a function from modifying my array?
Declare the parameter with const, for example const int v[]. Any attempt to write through it becomes a compile error.
Can I pass an array to a function and keep the original untouched?
Yes. Copy the array into a second buffer with memcpy and pass the copy, or have the function write its result into a separate output array.
Does passing an array copy all its elements onto the stack?
No. Only one address is passed, so the cost is constant. The exception is an array inside a struct passed by value, which is copied entirely.
Is this the same on a microcontroller as on a PC?
The language rules are identical. Only sizes differ: an address is typically 4 bytes on a 32-bit Cortex-M and 8 bytes on a 64-bit desktop.
Is this free C programming course suitable for beginners?
Yes. Each lecture starts from first principles, includes runnable code and expected output, and builds toward practical embedded C programming skills.
Keep Going with the Free C Programming Course
Next up: writing general array functions that work for any length. Practise the demo from this lecture first, then continue your free embedded C course journey.

2 Comments