The correct answer is: D. All of the above
You can pass copies of individual structure members, copies of entire structures, and pointers to structures to functions.
- Passing copies of individual structure members
When you pass a structure member to a function, the function receives a copy of the member’s value. This means that any changes you make to the member in the function will not be reflected in the original structure.
For example, consider the following code:
“`struct my_struct {
int x;
int y;
};
void change_x(my_struct *s) {
s->x = 10;
}
int main() {
my_struct s = {1, 2};
change_x(&s);
printf(“%d\n”, s.x); // prints 10
}
“`
In this example, the function change_x()
receives a copy of the structure member s.x
. The function changes the value of s.x
to 10, but this change does not affect the original structure. When the function returns, the value of s.x
is still 2.
- Passing copies of entire structures
When you pass an entire structure to a function, the function receives a copy of the entire structure. This means that any changes you make to the structure in the function will be reflected in the original structure.
For example, consider the following code:
“`struct my_struct {
int x;
int y;
};
void change_structure(my_struct s) {
s.x = 10;
s.y = 20;
}
int main() {
my_struct s = {1, 2};
change_structure(s);
printf(“%d %d\n”, s.x, s.y); // prints 10 20
}
“`
In this example, the function change_structure()
receives a copy of the entire structure s
. The function changes the values of s.x
and s.y
to 10 and 20, respectively. These changes are reflected in the original structure, so when the function returns, the value of s.x
is 10 and the value of s.y
is 20.
- Passing pointers to structures
When you pass a pointer to a structure to a function, the function receives a pointer to the original structure. This means that any changes you make to the structure through the pointer will be reflected in the original structure.
For example, consider the following code:
“`struct my_struct {
int x;
int y;
};
void change_structure_pointer(my_struct *s) {
s->x = 10;
s->y = 20;
}
int main() {
my_struct s = {1, 2};
change_structure_pointer(&s);
printf(“%d %d\n”, s.x, s.y); // prints 10 20
}
“`
In this example, the function change_structure_pointer()
receives a pointer to the structure s
. The function changes the values of s.x
and s.y
to 10 and 20, respectively. These changes are reflected in the original structure, so when the function returns, the value of s.x
is 10 and the value of s.y
is 20.