What are Passing Struct Members to Functions- C Programming Course Online

🚀 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 →

PREV_LEC  |  NEXT_LEC

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

passing structure members to functions in C call by value call by address UART configuration lab C interview questions free C programming course

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 passWhat the function receivesCan it change the original?
A member, like led.levelA copy of that member’s valueNo
The address of a member, like &led.levelA pointer to that memberYes
The whole structure or a pointer to itCopy of the structure, or its addressCopy: 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

1

By value

led.level is copied into the parameter. The function edits the copy; led.level keeps its value.

2

By address

&led.level is copied. The function follows the address and edits led.level itself.

3

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

OutputWhy
BRR = 13816,000,000 divided by 115,200 gives 138 with integer division
CTRL = 0x00000000 for 8N18 data bits, 1 stop bit and no parity set none of the control bits
CTRL = 0x00003400 for 9E2Bit 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

ConceptSeen in the lab as
Nested structurecfg.frame.parity
Nested initialization{ 115200, { 8, 1, 'N' } }
Pointer to structureregs->brr, cfg->baud
Chained arrow and dotcfg->frame.data_bits
Writing through a pointerThe function fills fake in main
const pointerconst 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->baud inside uart_apply and read the compiler error caused by const.

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.level means &(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 const on 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.member to 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.

  1. Which expression reaches the seconds field in struct reading r1 where the inner member is named taken?

    A. r1.ss   B. r1.taken.ss   C. r1->taken.ss   D. r1.stamp_in.ss

    Show answer

    B. You chain dots through the member name, not the type tag.

  2. 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.

  3. 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.

  4. If p points to struct motor, which is equivalent to p->rpm?

    A. *p.rpm   B. (*p).rpm   C. &p.rpm   D. p.rpm

    Show answer

    B. The parentheses are needed because dot binds tighter than the star.

  5. If sizeof(struct motor) is 20 and p points to fleet[0], what is the byte difference between p + 2 and p?

    Show answer

    40 bytes. Pointer arithmetic moves in whole-structure steps.

  6. What does *cp->sink give when sink is an int * member?

    Show answer

    The int that sink points to, because it is read as *(cp->sink).

  7. After struct holder b = a; where a has a pointer member, do a and b point to the same data?

    Show answer

    Yes. Structure assignment copies the address, not the pointed-to data (a shallow copy).

  8. A function receives int level from led.level. After the call, can it have changed led.level?

    Show answer

    No. It received a copy.

  9. What should the parameter type be if a function must modify led.level?

    Show answer

    int *, called as f(&led.level).

  10. Why use const struct uart_cfg *cfg in 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 ideaALT text
Copy of a value going into a function while the original stays behindPassing structure members to functions in C by value leaves the original unchanged
Address of a member entering a functionPassing structure members to functions in C by address in a free embedded C course
UART register block with config fields feeding itUART 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.

PREV_LEC  |  NEXT_LEC

💬 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 →