Lesson 20: Pass by address — a swap that works
Remember the broken swap from lesson 10? The function received copies of x and y, swapped the copies — and the originals stayed put. Today we fix it: void swap(int *a, int *b) receives addresses, and we call it with swap(&x, &y);. Writing through *a and *b changes the caller's real variables. This i
Asking a handyman to fix a photo of your living room won't help: he'll fix the photo. Lesson-10's swap received 'photos' (copies). When you hand over the address and key (&x), he walks in and changes the real living room.
- pass by value
- C's default: the function receives a copy. Changing the copy doesn't touch the original — which is why lesson-10's swap failed.
- pass by address
- Pass &x instead of x. The function writes through the pointer and changes the real variable.
- out-parameter
- A pointer the function writes a result through — how you 'return' more than one value.
- pointer to struct
- A pointer holding a struct's address: struct Student *s = &st;.
- the arrow operator ->
- s->grade is shorthand for (*s).grade: go to the struct at the address and take the field.