C Structure & Functions
In this page:
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: