🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Array of Structures Arguments
Free C Programming Course for Embedded Systems · Structure and Union · Lecture 20 · Quiz and Interview Questions
Real firmware rarely handles one structure. It handles a table of them: ADC channels, GPIO pin descriptors, command entries, sensor records. In this final lecture of the section of our free C programming course you learn how passing an array of structures to a function in C works, why the function can modify your data, and why sizeof betrays you inside the function.
We finish with a practice quiz and interview questions, so this lecture doubles as revision for anyone following this free embedded C course and aiming at embedded C programming jobs.
Table of Contents
What You Will Learn
After this lecture you can:
- Pass an array of structures together with its element count.
- Explain why the callee can modify the original elements.
- Write read-only helpers with a const pointer parameter.
- Avoid the sizeof-on-parameter bug.
- Answer common interview questions on structures and functions.
Prerequisites
You need lectures 16 to 19 of this chapter, plus arrays and pointer arithmetic from the earlier chapters of this free C tutorial.
How an Array of Structures Is Passed
A structure variable is copied when passed. An array is different: when you write the array name in a function call, it is converted to a pointer to its first element. So passing an array of structures never copies the elements. The function receives the address of element zero and works on the original array. That is why a parameter written as struct adc_sample s[] and one written as struct adc_sample *s mean exactly the same thing.
Array name becomes a pointer to element 0
Because the function only receives an address, it has no idea how many elements there are. You must pass the count as a separate argument. Using size_t for that count is the idiomatic choice.
Complete Example: ADC Channels
The program stores four ADC readings. Three helpers take the array and its length: one computes the average, one finds the channel with the highest reading, and one clamps every reading to a limit and therefore modifies the original. The first two use const because they only read.
#include <stdio.h>
#include <stddef.h>
struct adc_sample {
unsigned channel;
unsigned raw; /* 12-bit reading, 0..4095 */
};
static unsigned average_raw(const struct adc_sample *s, size_t n)
{
unsigned long sum = 0;
for (size_t i = 0; i < n; i++)
sum += s[i].raw;
return n ? (unsigned)(sum / n) : 0;
}
static size_t index_of_max(const struct adc_sample *s, size_t n)
{
size_t best = 0;
for (size_t i = 1; i < n; i++)
if (s[i].raw > s[best].raw)
best = i;
return best;
}
static void clamp_all(struct adc_sample *s, size_t n, unsigned limit)
{
for (size_t i = 0; i < n; i++)
if (s[i].raw > limit)
s[i].raw = limit;
}
static void size_inside(struct adc_sample s[4])
{
printf("inside function: sizeof(s) = %zu\n", sizeof s);
}
int main(void)
{
struct adc_sample ch[4] = {
{ 0, 1200 }, { 1, 3900 }, { 2, 2048 }, { 3, 15 }
};
size_t n = sizeof ch / sizeof ch[0];
printf("elements = %zu\n", n);
printf("average = %u\n", average_raw(ch, n));
printf("max at channel %u\n", ch[index_of_max(ch, n)].channel);
clamp_all(ch, n, 3000);
printf("after clamp, ch[1].raw = %u\n", ch[1].raw);
printf("in main: sizeof(ch) = %zu\n", sizeof ch);
size_inside(ch);
return 0;
}
Build and run:
gcc -std=c11 -Wall -Wextra -o adc_array adc_array.c
./adc_array
Expected output (the sizeof lines assume a 64-bit PC; GCC also prints a warning about sizeof on the array parameter, which is exactly the point of the next section):
elements = 4
average = 1790
max at channel 1
after clamp, ch[1].raw = 3000
in main: sizeof(ch) = 32
inside function: sizeof(s) = 8
Check the arithmetic
(1200 + 3900 + 2048 + 15) divided by 4 is 7163 / 4 = 1790 with integer division. The clamp then lowers channel 1 from 3900 to 3000, proving the callee changed the caller’s array.
The sizeof Trap
In main, sizeof ch is 32 because ch is a real array of four 8-byte structures. Inside size_inside, the parameter s is a pointer despite the bracket syntax, so sizeof s is the size of a pointer: 8 bytes here, 4 on a 32-bit MCU. Computing the element count inside the function with sizeof s / sizeof s[0] therefore gives a wrong number. Always compute the count where the real array is visible and pass it down.
| Expression | In main (real array) | Inside function (parameter) |
|---|---|---|
sizeof ch / sizeof s | 32 | 8 (pointer size) |
| Element count by sizeof division | Correct | Wrong |
| Safe approach | Pass the element count as an extra argument | |
Real-World Use Cases
- A table of GPIO pin descriptors walked by an init function at start-up.
- A command table with names and handler pointers searched by a shell.
- A ring of sensor samples averaged or filtered by a helper.
Common Mistakes
| Mistake | Result | Fix |
|---|---|---|
| Not passing the element count | Loop runs past the array | Always pass n |
| Using sizeof on the array parameter | Wrong count | Compute in the caller |
| Forgetting const on read-only helpers | Accidental edits | Use const pointer |
| Off-by-one in the loop bound | Memory corruption | Use i < n |
| Expecting a copy of the array | Surprise changes in caller | Remember it is a pointer |
Best Practices
- Pair every array parameter with a
size_tcount. - Mark read-only array parameters
const. - Define a macro or compute the count once next to the array definition.
- Keep tables of structures
static constwhen they never change, so they can live in flash. - Write the loop using index notation first; switch to pointer walking only when it helps readability.
Practice Quiz
Try each question before opening the answer.
- A structure variable is passed to a function as an argument. The function changes a member. What does the caller see?
- A. The new value
- B. The old value
- C. A compile error
- D. Undefined behaviour
Show answer
B. The function works on a copy.
- Which operator accesses a member through a structure pointer?
- A. .
- B. ->
- C. &
- D. ::
Show answer
B. The arrow operator.
- Why is
(*p).xwritten with parentheses?- A. Style only
- B. The dot binds tighter than the star
- C. Required by the linker
- D. It makes x constant
Show answer
B. Without parentheses, p.x would be evaluated first.
- What does
const struct gpio_cfg *cprevent?- A. Reading members
- B. Passing NULL
- C. Writing members through c
- D. Taking its address
Show answer
C. The function cannot modify the structure through that pointer.
- Is it safe to return a copy of a local structure?
- A. Yes, the contents are copied
- B. No, always a dangling pointer
- C. Only with static
- D. Only with malloc
Show answer
A. Returning by value copies the data; only returning the address of a local is unsafe.
- An array of 4 structures of 8 bytes each is passed to a function. On a 32-bit MCU, what does sizeof on the array parameter give?
- A. 32
- B. 8
- C. 4
- D. 0
Show answer
C. The parameter is a pointer, which is 4 bytes on a 32-bit target.
- Which approach avoids the heap while returning a filled structure through a pointer?
- A. malloc in the function
- B. static global shared by all
- C. Caller supplies the storage
- D. Return a local address
Show answer
C. The caller owns the storage, so there is no allocation and no ownership problem.
- Two structure types have identical members but different names. Can one be assigned to the other?
- A. Yes
- B. No, they are different types
- C. Only with a cast of members
- D. Only inside main
Show answer
B. They are distinct types, so direct assignment is a compile error.
Interview Questions
1. How are structures passed to functions in C?
By value, so the function gets a copy. To share or modify the original, pass a pointer.
2. When would you pass a pointer to a structure instead of the structure?
When the function must modify it, or when the structure is large and copying is costly in time or stack.
3. What is the difference between the dot and arrow operators?
Dot works on a structure variable. Arrow works on a pointer to a structure and is shorthand for dereference plus dot.
4. Why is returning the address of a local variable a bug?
The local lives on the stack and is released on return, leaving a dangling pointer.
5. How can a C function return multiple values?
Return a structure containing them, or use output pointer parameters.
6. Why must you pass the element count with an array of structures?
The array decays to a pointer, so the function cannot recover the length from the parameter.
7. How does const help in structure-pointer parameters?
It documents read-only intent and lets the compiler reject accidental writes.
8. How would you design an API without malloc for a bare-metal driver?
Provide an init function that takes a caller-owned structure pointer and returns a status code.
9. Does a structure containing an array copy that array on pass by value?
Yes, the whole array member is copied along with the rest of the structure.
10. What stack concern exists with by-value structure arguments in ISRs?
Each call copies the structure to a small interrupt stack, risking overflow; use a pointer instead.
Summary and Conclusion
Key Takeaways
- Structure by value: copied, caller safe.
- Pointer to structure: no copy, callee may modify, use const to restrict.
- Return by value: safe copy; return pointer: mind ownership and lifetime.
- Arrays of structures decay to a pointer, so pass the count separately and never use sizeof on the parameter.
You now know every common way to pass structures into and out of functions in C, which is the foundation of driver APIs in embedded C programming. Keep practising with the quiz above, then continue with the next topic in this free C programming course.
Suggested Images
- Diagram of an array decaying into a pointer to its first structure. ALT: passing array of structures to function in C diagram, free C programming course
- Table summarising by-value, pointer and return patterns. ALT: embedded C programming structure function argument patterns, free embedded C course
- Screenshot of the sizeof warning in GCC. ALT: sizeof array parameter warning embedded C tutorial, free C tutorial
Frequently Asked Questions
Can I pass an array of structures to a function in C?
Yes. The array name becomes a pointer to the first element, and you pass the element count as a separate argument.
Does the function copy the whole array?
No. Only the address is passed, so changes inside the function affect the original array.
Why does sizeof give the pointer size inside my function?
Array parameters are adjusted to pointers, so sizeof returns the size of a pointer.
Should I write s[] or *s for the parameter?
They are equivalent. Choose whichever communicates intent; many teams prefer the pointer form with const.
How do I stop a function from modifying the array?
Declare the parameter as a pointer to const structure.
Is this course really free?
Yes. EmbeddedPathashala offers this free C programming course and other free embedded and Linux courses.
Finished This Section of the Free C Course
Revisit the quiz, then continue to the next lecture in our free embedded C course.

2 Comments