Struct and function
- C course
- Intermediate
- Lesson 32/116
- 5 min
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.
Practice 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);.
Starter code
#include <stdio.h>
// Define struct Person (name[32] and age)
// Write void birthday(struct Person *p), increment age via p
// In main declare p1, call birthday, print result
int main(void) {
return 0;
}Sample 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;
}Expected output
26
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pointer parameter signature
void printPerson(struct Person ____) { printf("%d
", p->age); }
void printPerson(struct Person *p) { printf("%d
", p->age); }
Explanation: *p is the struct Person pointer parameter.
2 Match the call forms
| Term | Meaning |
|---|---|
printPerson(&p1) |
Pointer call |
printPerson(p1) |
Value call |
void f(struct Person*) |
Pointer parameter |
void f(struct Person) |
Value parameter |
3 Most efficient way to pass a large struct to a function?
- By value
- By pointer Correct answer
- As an array
- As a global variable
Explanation: A pointer copies only the address; it's the efficient choice for large structs.