Course contentsShow
← C
Lesson 605 of 1,2199. Structures and UnionsFree lesson

Structs as function arguments by value

Structs as function arguments by value

What you'll learn: How to pass an entire structure to a function so that the function works with a private copy of the data.

The Photocopy Principle

When you pass a simple variable like an int to a function, C creates a copy of that value. The same is true for structures. Think of it like a photocopy: if you give a friend a photocopy of a drawing and they scribble on it, your original drawing remains untouched.

When you pass a struct "by value," the computer allocates new memory for the function and copies every single member of the structure into that new space.

Seeing it in Action

Imagine we are managing a player's coordinates in a video game. We want a function that displays the player's position but also tries (and fails) to reset those coordinates to zero.

#include <stdio.h>

struct Point {
    int x;
    int y;
};

// This function receives a COPY of the struct
void processPoint(struct Point p) {
    printf("Inside function: x = %d, y = %d\n", p.x, p.y);
    
    // Changing the copy does not affect the original
    p.x = 0;
    p.y = 0;
    printf("Inside function after change: x = %d, y = %d\n", p.x, p.y);
}

int main() {
    struct Point player = {10, 25};

    printf("Before function: x = %d, y = %d\n", player.x, player.y);
    
    processPoint(player);
    
    // The original 'player' is still {10, 25}
    printf("After function: x = %d, y = %d\n", player.x, player.y);

    return 0;
}

Why use this?

Passing by value is extremely safe. Because the function is working on a duplicate, you don't have to worry about the function accidentally corrupting your original data. It encapsulates the data perfectly.

However, there is a small trade-off. If your structure is massive—containing hundreds of variables or large arrays—copying all that data every time you call a function can slow down your program and use extra memory. For small-to-medium structures, though, passing by value is a clean and straightforward way to keep your data secure.

Key takeaway

Passing a struct by value creates a complete, independent copy; any changes made inside the function disappear once the function ends.