How to Pass Array Elements to Functions- C Programming Course For Engineering Students

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Arrays · Lecture 11

Pass Array Elements to Functions

Pass array elements to function in C with call by value, prototypes and addresses. Includes a tested sensor-limit program and a preview of whole-array passing.

11
Arrays chapter
12 min
Read and practise
100%
Free forever

In this lecture of our free C programming course you learn to pass array elements to function calls in C and understand exactly what the function receives.

We use a sensor limit checker as the running example, write it in clean modern C with prototypes, and finish with a short preview of why passing a whole array behaves differently.

What You Will Learn

  • How to pass array elements to function in C by value
  • Why a function cannot change the caller’s element through a copy
  • Passing the address of an element to allow changes
  • Prototypes and return types in modern C
  • A first look at why whole arrays lose their length

Prerequisites

  • Earlier lectures of this arrays chapter and the functions chapter
  • Understanding of function definition, return values and if conditions
  • A C compiler with -Wall -Wextra available

Pass Array Elements to a Function: The Basic Idea

An individual array element, such as samples[2], is just an int variable that happens to live inside an array. You can use it anywhere you can use a plain variable, including as an argument to a function. When you do, C evaluates the element, takes its value, and gives the function its own private copy. This is called call by value, and it is the only way C passes ordinary arguments.

Call by value: the function works on a copy

samples124789133
callover_limit(samples[0]) copies the value 12
parameter12
effectthe array element stays 12, whatever the function does

Write Modern C: Prototypes and Return Types

Older textbooks show functions written as check(int num), with no return type and defined after main(). Those programs relied on two features that the C99 standard removed: implicit int return types and calling a function that was never declared. Recent compilers reject them or warn loudly, and GCC 14 and later turn them into errors by default. Always write a return type for every function, and declare the function (give its prototype) before you call it. A prototype lets the compiler check that the number and types of your arguments are correct.

static int  over_limit(int reading);       /* prototype: name, argument type, return type */

Example: Checking Each Sample Against a Limit

The next program passes each element of a sample array to over_limit(), which returns 1 when the reading is above the limit and 0 otherwise. Because a comparison in C produces 0 or 1, the function body is a single line. The caller counts the alarms. Then two helper functions show what a function can and cannot change.

#include <stdio.h>

#define LIMIT 40

static int over_limit(int reading);
static void try_to_change(int value);
static void really_change(int *slot);

int main(void)
{
    int samples[5] = {12, 47, 8, 91, 33};
    int alarms = 0;
    int i;

    for (i = 0; i < 5; i++) {
        if (over_limit(samples[i])) {
            printf("samples[%d] = %2d  -> ALARM\n", i, samples[i]);
            alarms++;
        } else {
            printf("samples[%d] = %2d  -> ok\n", i, samples[i]);
        }
    }
    printf("alarms raised: %d\n", alarms);

    try_to_change(samples[0]);
    printf("after try_to_change : samples[0] = %d\n", samples[0]);

    really_change(&samples[0]);
    printf("after really_change : samples[0] = %d\n", samples[0]);
    return 0;
}

static int over_limit(int reading)
{
    return reading > LIMIT;
}

static void try_to_change(int value)
{
    value = value + 100;          /* only the local copy changes */
}

static void really_change(int *slot)
{
    *slot = *slot + 100;          /* writes into the caller's array element */
}
$ gcc -std=c17 -Wall -Wextra -o ep_pass_elem ep_pass_elem.c
$ ./ep_pass_elem
samples[0] = 12  -> ok
samples[1] = 47  -> ALARM
samples[2] =  8  -> ok
samples[3] = 91  -> ALARM
samples[4] = 33  -> ok
alarms raised: 2
after try_to_change : samples[0] = 12
after really_change : samples[0] = 112

What the output proves

  • Only 47 and 91 are above the limit of 40, so two alarms are raised.
  • try_to_change(samples[0]) added 100 to its own copy. The array element stayed at 12.
  • really_change(&samples[0]) received the address of the element and wrote through it, so the element became 112.

Passing the Address of an Element

To let a function change a caller’s variable, you pass its address with the & operator. The function declares the parameter as a pointer, written with *, and writes with *slot = .... Pointers have their own chapter in this course, so for now remember one sentence: the star means write into the caller’s variable. Even then the pointer itself is passed by value; what you gain is permission to change what it points at.

Passing &samples[0] gives the function the location, not a copy

callersamples[0] = 12
calleeslot holds the address of samples[0]
write*slot = *slot + 100
resultsamples[0] = 112

A Preview: Passing the Whole Array

What if you pass samples itself instead of one element? Then C does not copy the whole array. It passes the address of the first element, and the parameter inside the function is really a pointer even if you wrote it with square brackets. A tiny experiment shows the consequence.

#include <stdio.h>

static void peek(int data[])
{
    printf("inside peek : sizeof data = %zu\n", sizeof data);
}

int main(void)
{
    int table[10] = {0};

    printf("inside main : sizeof table = %zu\n", sizeof table);
    peek(table);
    return 0;
}
$ gcc -std=c17 -Wall -Wextra -o ep_pass_preview ep_pass_preview.c
$ ./ep_pass_preview
inside main : sizeof table = 40
inside peek : sizeof data = 8

GCC warns that sizeof on an array parameter returns the size of a pointer, and the output confirms it: 40 bytes in main() but 8 bytes inside peek() on a 64-bit machine. The function has lost the length. That is why functions that receive a whole array also receive the element count as a separate parameter. We cover it fully in the next lecture.

Three Ways to Hand Array Data to a Function

What you passExample callWhat the function receivesCan it change the original?
One element valueover_limit(a[i])A copy of the valueNo
One element addressreally_change(&a[i])A pointer to that elementYes, that one element
The whole arraypeek(a)A pointer to element 0, no lengthYes, every element

Real-World Uses in Embedded C Programming

Firmware passes array elements to functions all day long. Typical places where you pass array elements to function calls are listed here.

  • Calling a decode function once for each received byte stored in a buffer.
  • Checking every ADC channel result against its own alarm threshold.
  • Passing a single register image to a function that prints a human readable status.
  • Handing the address of one array slot to a driver so it can store a measurement result directly.
  • Applying a small calibration function to each reading before it is logged.

Mistakes When You Pass Array Elements to Function Calls

MistakeSymptomFix
Expecting a function to change a[i] passed by valueThe array never changesPass &a[i] and use a pointer parameter
Calling a function before declaring itWarning or error: implicit declarationAdd a prototype above main()
Omitting the return typeError in modern compilers, undefined result in old onesWrite int, void or the real type
Passing a where a[i] was meantType mismatch warningRead the parameter type in the prototype
Using an index outside the array, such as samples[5] for 5 elementsGarbage value passed in, undefined behaviourKeep the index below the array length
Passing an expression with side effects, like f(a[i++]), to a macroThe side effect may run twiceUse a real function, not a macro

Best Practices to Pass Array Elements to Function Safely

  • Make helper functions static when they are used by one file, so they do not collide with other files.
  • Keep small functions pure: input in, result out, no hidden global state. They are easy to test on a PC and then move to the target.
  • Performance: passing an int by value is usually a register move, essentially free. Inlining small functions removes the call entirely at normal optimisation levels.
  • Compile with -Wall -Wextra to catch missing prototypes and type mismatches.
  • Security: check the index before you read a[i] and pass it on. A function cannot defend itself against a value that was already read out of bounds.

Summary and Key Takeaways

  • You can pass array elements to function calls exactly like ordinary variables.
  • C passes arguments by value, so the function changes only its own copy.
  • Pass &a[i] to let a function write into one element.
  • Always declare functions with a prototype and a return type.
  • A whole array decays to a pointer, so its length must be passed separately.

Conclusion

You can now pass array elements to function calls in C, predict exactly what the function can and cannot change, and write the clean, prototyped style that modern compilers expect. This is where arrays and functions meet, which is the heart of embedded C programming: small, testable functions that act on data buffers. The next lecture in this free C course passes the whole array to a function, and the length parameter you just met becomes essential.

Topics Covered in This Free Embedded C Lecture

free c programming coursefree c tutorialc programming for embedded systemsembedded c programmingfree embedded c coursec arrays for beginnerspass array elements to function in Ccall by valuefunction prototype in C

Frequently Asked Questions

How do I pass an array element to a function in C?

Write the element as the argument, for example f(a[i]). The function receives a copy of its value through its parameter.

Can the function change the array element I pass?

Not if you pass the element by value. To allow a change, pass its address with &a[i] and use a pointer parameter in the function.

What is call by value?

It means the argument is evaluated and its value is copied into the parameter. The function works on the copy, not on the original variable.

Why do I need a function prototype?

A prototype tells the compiler the function name, parameter types and return type before the call, so it can check your arguments. Modern C requires it.

What happens if I pass the whole array instead of one element?

The array turns into a pointer to its first element and the length is lost, so the function needs the element count as another argument.

Why does GCC reject old style code like check(int num)?

Implicit int and implicit function declaration were removed from C in 1999, and recent GCC releases treat them as errors by default.

Continue the Free Embedded C Course

Next up: passing a whole array to a function. Modify today’s program to use a different limit for each sample and see how many alarms it raises.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →