← Back to C Course | Chapter 8: Structures & Unions | Lesson 3 of 7

C Structure & Functions

Passing Structures by Value

This mirrors how any variable is passed by value in C by default -- the function receives its own independent copy of every member, so it's safe from accidental modification but also can't report changes back to the caller.

Example: Passing Structures by Value

c
#include <stdio.h>
struct Student { int age; };
void tryChange(struct Student s) {
	s.age = 99;
}
int main() {
	struct Student s = {20};
	tryChange(s);
	printf("%d", s.age);
	return 0;
}

Passing Structures by Reference

Passing a pointer (like void update(struct Student *s)) avoids copying potentially large amounts of data on every function call, and is the standard approach once a structure has more than a couple of small fields.

Example: Passing Structures by Reference

c
#include <stdio.h>
struct Student { int age; };
void update(struct Student *s) {
	s->age = 21;
}
int main() {
	struct Student s = {20};
	update(&s);
	printf("%d", s.age);
	return 0;
}

Modifying Structures in Functions

Inside the function, you use the arrow operator (s->name = "Bob") to modify fields through the pointer -- this directly changes the original structure the caller passed in, unlike the pass-by-value approach.

Example: Modifying Structures in Functions

c
#include <stdio.h>
struct Student { char name[20]; };
void rename2(struct Student *s) {
	s->name[0] = 'B';
}
int main() {
	struct Student s = {"Ann"};
	rename2(&s);
	printf("%s", s.name);
	return 0;
}

Returning Structures from Functions

A function like struct Point makePoint(int x, int y) { struct Point p = {x, y}; return p; } builds and hands back a fully-formed structure, which is a clean way to construct complex data without needing an out-parameter.

Example: Returning Structures from Functions

c
#include <stdio.h>
struct Point { int x, y; };
struct Point makePoint(int x, int y) {
	struct Point p = {x, y};
	return p;
}
int main() {
	struct Point p = makePoint(3, 4);
	printf("%d %d", p.x, p.y);
	return 0;
}

Comparing Performance

For a structure with many members or large arrays inside it, copying by value on every function call adds up -- profiling real programs shows pointer-passing is almost always faster once a structure grows beyond a few small fields.

Example: Comparing Performance

c
#include <stdio.h>
struct Big { int data[100]; };
void byRef(struct Big *b) {
	b->data[0] = 1;
}
int main() {
	struct Big b = {0};
	byRef(&b);
	printf("%d", b.data[0]);
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.