C
Struct and function
Learn to pass structs to functions by value and by pointer.
Passing by value and by pointer
You can pass a struct to a function in two ways: by value or by pointer. Passing by value copies the entire struct; that's expensive for large structs. Passing by pointer copies only the address; that's efficient.
Example: void printPerson(struct Person *p) { printf("%d\n", p->age); }. Call: printPerson(&p1);. Functions taking a pointer can modify the struct; be aware of side effects. If the function won't modify the struct, using const struct Person *p states the intent clearly.
const struct pointer
To state that a function won't modify the struct, use const struct Person *p. The compiler rejects assignments like p->age = ... inside the function.
Example: int getAge(const struct Person *p) { return p->age; }. This function only reads the struct; it has no side effects. The caller gets a guarantee that the struct won't change. This is an important safety pattern in large C projects; it clarifies API contracts. The const wording warns both the compiler and the human reader.
Exercise Write a birthday function
Define struct Person with char name[32]; and int age;. Write void birthday(struct Person *p); in the body increment age with p->age++;. In main, declare struct Person p1 = {"Ali", 25};, call birthday(&p1);, print with printf("%d\n", p1.age);.
Show example solution
#include <stdio.h>
struct Person {
char name[32];
int age;
};
void birthday(struct Person *p) {
p->age++;
}
int main(void) {
struct Person p1 = {"Ali", 25};
birthday(&p1);
printf("%d\n", p1.age);
return 0;
}
Test yourself
-
Pointer parameter signature
void printPerson(struct Person ____) { printf("%d
", p->age); }
Show answer
void printPerson(struct Person *p) { printf("%d
", p->age); }
-
Match the call forms
- printPerson(&p1)
- Pointer call
- printPerson(p1)
- Value call
- void f(struct Person*)
- Pointer parameter
- void f(struct Person)
- Value parameter
-
Most efficient way to pass a large struct to a function?
- By value
- By pointer
- As an array
- As a global variable
Show answer
By pointer — A pointer copies only the address; it's the efficient choice for large structs.
Next lesson: Nested structs