Passing a big struct to a function copies all of it, and the function can't change the original. So we usually pass a pointer to the struct instead.
With a pointer, you reach a field with the arrow -> instead of the dot:
#include <stdio.h>
typedef struct {
char owner[20];
int balance;
} Account;
void deposit(Account *acc, int amount) {
acc->balance += amount;
}
void show(Account *acc) {
printf("%s has %d\n", acc->owner, acc->balance);
}
int main() {
Account a;
sprintf(a.owner, "Ravi");
a.balance = 100;
deposit(&a, 50);
deposit(&a, 25);
show(&a);
return 0;
}Output
Ravi has 175
Account *acc: the function receives the address of an account.acc->balance: "the balance of the account thataccpoints to".deposit(&a, 50): we pass the address, so the real account changes.
Remember: Use the dot
.with a struct variable, and the arrow->with a pointer to a struct. (acc->balanceis short for(*acc).balance.)
Think of it like this: The arrow looks like it is pointing: "follow this pointer, then take the field".