Pass a Record to a Function
The desk clerk prints kit labels from more than one record. Give the printing function a struct Kit parameter: it receives a copy of the member values. Even assigning a different kit.pieces inside the function changes only that copy. This differs from the earlier array parameters, which gave access to the caller's elements.
#include <stdio.h>
struct Kit {
const char *name;
int pieces;
};
void show_kit(struct Kit kit) {
printf("%s: %d pieces\n", kit.name, kit.pieces);
}
int main(void) {
struct Kit kit = {"Paint", 4};
show_kit(kit);
return 0;
}
Run it to see Paint: 4 pieces. Both variables are named kit, but they live in different function scopes. The call copies the record in main into the parameter.
Copying a pointer member copies its address, not the string it points to. Both name pointers refer to the same "Paint" literal. To update the caller's integer member, a function would instead need a struct Kit * parameter and use ->, as in the preceding member-access lesson.