Pointers and structs
C passes everything by value. To let a function change your data, you pass the value of its address.
- Group fields with struct and access them with . and ->
- Explain why a function needs a pointer to modify its caller's data
- Bound every string write by the size of its buffer
A struct groups related fields into one value:
struct Person {
char name[50];
int age;
};
sizeof(struct Person) is 56, not 54: the compiler adds two bytes of padding after name so that age starts at an address divisible by four, the alignment an int needs. Lesson 3 draws this byte by byte.
Changing the caller’s data
C passes every argument by value: the function gets a copy. To let a function modify my_person, the program passes a copy of its address instead:
void change_person(struct Person *p, char *new_name, int new_age) {
sprintf(p->name, "%s", new_name);
p->age = new_age;
}
struct Person my_person;
struct Person *my_pointer = &my_person;
change_person(my_pointer, "John", 25);
p->age is shorthand for (*p).age: follow the pointer, then pick the field. The pointer itself is copied — eight bytes — but it points at the original, so every write lands in main’s struct.
Passing by value would also copy all 56 bytes on every call. For large structs, pointers are faster as well as necessary for modification; when a function only reads, const struct Person *p says so and lets the compiler enforce it.
Bound every write
sprintf(p->name, "%s", new_name) copies however many characters new_name has. name holds 50 bytes; a 60-character name would overwrite age and whatever lies beyond. The bounded version cannot overflow:
snprintf(p->name, sizeof p->name, "%s", new_name);
It truncates instead, and always writes the terminating zero. Also, since string literals such as "John" must not be modified, the parameter is better declared const char *new_name.
Try it yourself. Call change_person with a 70-character name, compile with gcc -fsanitize=address, and read the report. Then switch to snprintf and confirm the name is cut at 49 characters. Finally, write void birthday(struct Person p) that does p.age++ and show that it has no effect on the caller.