🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Chapter 10 · Lecture 15
Passing Struct Members to Functions
Learn passing structure members to functions in C by value and by address, then build a UART configuration lab. Includes a quiz and interview questions. Free embedded C course.
Topics in This Free C Tutorial
Structures can be given to functions in several ways: one member at a time, the whole structure, or a pointer to it. This lecture covers the first and most basic way, passing structure members to functions in C, and then ties the whole chapter together in a hands-on UART configuration lab. If you are working through this free C programming course to master embedded C programming, finish this lecture with the quiz and interview questions at the end; they test exactly what firmware interviewers like to ask about structures and pointers.
What You Will Learn
- The three ways a structure can be handed to a function
- Passing a structure member by value, and why the original does not change
- Passing the address of a member so the function can modify it
- How array members such as strings behave as arguments
- A complete UART lab using nested structures and structure pointers
- A quiz and interview questions covering the whole chapter section
Prerequisites
You should know structure members, nested structures, pointers to structures and pointer members from the previous lectures, plus ordinary call by value and call by address with simple variables.
Ways of Passing Structure Members to Functions in C
There are three options, and a function can likewise return a member, a whole structure or a pointer to a structure. In this lecture we focus on the first option; the others follow in later lectures.
| What you pass | What the function receives | Can it change the original? |
|---|---|---|
A member, like led.level | A copy of that member’s value | No |
The address of a member, like &led.level | A pointer to that member | Yes |
| The whole structure or a pointer to it | Copy of the structure, or its address | Copy: no. Pointer: yes |
Passing Structure Members to Functions in C
A structure member is an ordinary variable as far as a function call is concerned. If you write toggle(led.level), the function receives a copy of the integer. Whatever it does to its copy is invisible to the caller. To let the function change the real member, pass its address with &led.level and receive it as a pointer.
By value versus by address
By value
led.level is copied into the parameter. The function edits the copy; led.level keeps its value.
By address
&led.level is copied. The function follows the address and edits led.level itself.
Array member
led.label becomes a pointer to its first character, so the function can change the text.
Example: A Pin Configuration
Save the program below as f1_pass_members.c. It uses one function that receives a copy, one that receives an address and one that rewrites a string member.
#include <stdio.h>
#include <string.h>
struct pin_cfg {
char label[8];
int port;
int level;
};
static void toggle_copy(int level)
{
level = !level;
printf(" inside toggle_copy : level = %d\n", level);
}
static void toggle_real(int *level)
{
*level = !*level;
printf(" inside toggle_real : *level = %d\n", *level);
}
static void relabel(char *dst, const char *src)
{
strcpy(dst, src);
}
int main(void)
{
struct pin_cfg led = { "LED1", 2, 0 };
printf("start: %s level=%d\n", led.label, led.level);
toggle_copy(led.level);
printf("after toggle_copy: level=%d\n", led.level);
toggle_real(&led.level);
printf("after toggle_real: level=%d\n", led.level);
relabel(led.label, "STAT");
printf("after relabel : %s\n", led.label);
return 0;
}
Build and Run
$ gcc -Wall -Wextra -std=c11 f1_pass_members.c -o f1
$ ./f1
start: LED1 level=0
inside toggle_copy : level = 1
after toggle_copy: level=0
inside toggle_real : *level = 1
after toggle_real: level=1
after relabel : STAT
The first call proves the point: the function printed 1 for its own copy, yet led.level stayed 0. The second call changed the real member, and the third rewrote the text. Note that relabel copies up to the destination size, so the new text must fit in the 8-byte array. When the length is not certain, check it first or use a bounded copy.
Lab: UART Configuration With Nested Structures and Pointers
This lab combines the chapter: a nested structure for the frame format, a pointer to the configuration, and a pointer to a register block. On real hardware the register pointer would hold the peripheral’s base address; here we use an ordinary variable so you can run it on a PC. The register bit positions below belong to our teaching model and are not tied to any specific chip.
Step 1: The Code
#include <stdio.h>
#include <stdint.h>
struct uart_frame {
uint8_t data_bits;
uint8_t stop_bits;
char parity; /* 'N', 'E' or 'O' */
};
struct uart_cfg {
uint32_t baud;
struct uart_frame frame;
};
struct uart_regs {
uint32_t ctrl;
uint32_t brr;
uint32_t status;
};
static void uart_apply(struct uart_regs *regs, const struct uart_cfg *cfg,
uint32_t clk_hz)
{
regs->brr = clk_hz / cfg->baud;
regs->ctrl = 0;
regs->ctrl |= (uint32_t)(cfg->frame.data_bits == 9) << 12;
regs->ctrl |= (uint32_t)(cfg->frame.stop_bits == 2) << 13;
if (cfg->frame.parity != 'N') {
regs->ctrl |= 1u << 10;
regs->ctrl |= (uint32_t)(cfg->frame.parity == 'O') << 9;
}
regs->status = 1;
}
static void uart_dump(const struct uart_regs *regs)
{
printf("CTRL = 0x%08X\n", (unsigned)regs->ctrl);
printf("BRR = %u\n", (unsigned)regs->brr);
printf("STATUS = 0x%08X\n", (unsigned)regs->status);
}
int main(void)
{
struct uart_cfg cfg = { 115200, { 8, 1, 'N' } };
struct uart_regs fake = { 0, 0, 0 };
uart_apply(&fake, &cfg, 16000000u);
printf("--- 8N1 @ 115200, 16 MHz clock ---\n");
uart_dump(&fake);
cfg.frame.data_bits = 9;
cfg.frame.stop_bits = 2;
cfg.frame.parity = 'E';
uart_apply(&fake, &cfg, 16000000u);
printf("--- 9E2 @ 115200, 16 MHz clock ---\n");
uart_dump(&fake);
return 0;
}
Step 2: Build and Run
$ gcc -Wall -Wextra -std=c11 lab_uart.c -o lab_uart
$ ./lab_uart
--- 8N1 @ 115200, 16 MHz clock ---
CTRL = 0x00000000
BRR = 138
STATUS = 0x00000001
--- 9E2 @ 115200, 16 MHz clock ---
CTRL = 0x00003400
BRR = 138
STATUS = 0x00000001
Step 3: Understand the Output
| Output | Why |
|---|---|
| BRR = 138 | 16,000,000 divided by 115,200 gives 138 with integer division |
| CTRL = 0x00000000 for 8N1 | 8 data bits, 1 stop bit and no parity set none of the control bits |
| CTRL = 0x00003400 for 9E2 | Bit 12 (9 data bits) is 0x1000, bit 13 (2 stop bits) is 0x2000 and bit 10 (parity on) is 0x400; even parity leaves bit 9 clear. The sum is 0x3400 |
Where each lab idea appears
| Concept | Seen in the lab as |
|---|---|
| Nested structure | cfg.frame.parity |
| Nested initialization | { 115200, { 8, 1, 'N' } } |
| Pointer to structure | regs->brr, cfg->baud |
| Chained arrow and dot | cfg->frame.data_bits |
| Writing through a pointer | The function fills fake in main |
const pointer | const struct uart_cfg *cfg promises not to modify the configuration |
Step 4: Try It Yourself
- Change the baud rate to 9600 and predict the new BRR value before running.
- Add a 7-bit mode and decide which control bit it should set.
- Try writing to
cfg->baudinsideuart_applyand read the compiler error caused byconst.
Common Mistakes When Passing Structure Members to Functions in C
- Expecting a by-value member to change. The function only has a copy.
- Passing a member instead of its address.
toggle_real(led.level)fails to compile because an int is not a pointer. - Overflowing a string member. Check the length before copying into a fixed array.
- Operator precedence.
&led.levelmeans&(led.level), which is what you want.
Best Practices for Passing Structure Members to Functions in C
Guidelines
- Pass small members by value; pass addresses when the function must change data.
- Use
conston pointer parameters that are only read. - Prefer passing a pointer to the structure over many separate members when a function needs several fields.
- Validate sizes before copying text, since unchecked copies are a classic security flaw.
Summary and Key Takeaways
- A member passed by value is copied, so the function cannot change the original.
- Pass
&s.memberto let a function modify the member. - Array members decay to pointers and can be modified through the parameter.
- Nested structures, pointers to structures and chained operators combine naturally in driver code.
Conclusion
You can now hand structure members to functions in either style and read how a small driver combines everything in this part of Chapter 10. In the next lectures we pass whole structures, return structures and return pointers. Before moving on, test yourself below.
Chapter Quiz: Test Yourself
Try each question first. Click an answer to reveal it.
-
Which expression reaches the seconds field in
struct reading r1where the inner member is namedtaken?A.
r1.ssB.r1.taken.ssC.r1->taken.ssD.r1.stamp_in.ssShow answer
B. You chain dots through the member name, not the type tag.
-
An outer structure contains an inner structure by value. Where must the inner definition appear?
A. After the outer B. Anywhere C. Before the outer D. In a separate function
Show answer
C. Otherwise the compiler reports an incomplete type.
-
Which declaration is legal?
A. A structure containing itself B. A structure containing a pointer to itself
Show answer
B. A pointer has a fixed size; a self-containing structure would have infinite size.
-
If
ppoints tostruct motor, which is equivalent top->rpm?A.
*p.rpmB.(*p).rpmC.&p.rpmD.p.rpmShow answer
B. The parentheses are needed because dot binds tighter than the star.
-
If
sizeof(struct motor)is 20 andppoints tofleet[0], what is the byte difference betweenp + 2andp?Show answer
40 bytes. Pointer arithmetic moves in whole-structure steps.
-
What does
*cp->sinkgive whensinkis anint *member?Show answer
The int that sink points to, because it is read as
*(cp->sink). -
After
struct holder b = a;whereahas a pointer member, doaandbpoint to the same data?Show answer
Yes. Structure assignment copies the address, not the pointed-to data (a shallow copy).
-
A function receives
int levelfromled.level. After the call, can it have changedled.level?Show answer
No. It received a copy.
-
What should the parameter type be if a function must modify
led.level?Show answer
int *, called asf(&led.level). -
Why use
const struct uart_cfg *cfgin the lab?Show answer
It tells the compiler and the reader that the function will only read the configuration, and the compiler rejects accidental writes.
Interview Questions on Structures and Pointers
1. What is a nested structure and how do you access its members?
A nested structure has another structure as a member. You chain the dot operator, or use arrow then dot when you hold a pointer, for example cfg->frame.parity.
2. Why can a structure not contain itself but can contain a pointer to itself?
A self-contained structure would need infinite space. A pointer has a fixed size, so linked structures are possible.
3. What is the difference between . and ->?
Dot works on a structure variable; arrow works on a pointer to a structure and is shorthand for dereferencing then using dot.
4. Explain the precedence issue in *p.member.
Dot has higher precedence than the dereference star, so it is parsed as *(p.member). Use p->member or (*p).member.
5. What does sizeof of a nested structure depend on?
On the sizes of all members at every level plus any padding the compiler inserts for alignment.
6. What is a shallow copy of a structure?
Assignment copies every member byte for byte. Pointer members are copied as addresses, so both structures share the pointed-to data.
7. How would you let a function change one member of a structure?
Pass the address of that member, or a pointer to the whole structure, and write through the pointer.
8. Why is passing a large structure by pointer better on a microcontroller?
It avoids copying all bytes onto the stack and makes the call faster and cheaper in RAM.
9. How do you map a peripheral register block onto a structure?
Define a structure whose members match the register layout, then set a pointer to the peripheral’s base address, usually declared with volatile, and access registers with regs->ctrl.
10. What problem does const on a pointer parameter solve?
It documents and enforces that the function will not modify the pointed-to data.
Suggested Images for This Lecture
| Image idea | ALT text |
|---|---|
| Copy of a value going into a function while the original stays behind | Passing structure members to functions in C by value leaves the original unchanged |
| Address of a member entering a function | Passing structure members to functions in C by address in a free embedded C course |
| UART register block with config fields feeding it | UART configuration lab using nested structures and pointers in embedded C programming |
Frequently Asked Questions
Can a function change a structure member passed by value?
No. It changes only its own copy.
How do I pass a structure member by address?
Write &s.member in the call and declare the parameter as a pointer to the member’s type.
What happens when I pass an array member like a string?
The array name becomes a pointer to its first element, so the function can read and write the array contents.
Should I pass members or the whole structure?
Pass a single member when the function needs one value. Pass a pointer to the structure when it needs several fields.
Is the UART lab specific to one microcontroller?
No. It models a generic peripheral so you can run it on a PC. Real chips have their own register layouts.
Is this course free?
Yes. This free C programming course covers embedded C programming from the basics with tested examples in every lecture.
Keep Building Your Embedded C Skills
Next we pass whole structures to functions and return structures and pointers from them.

2 Comments