问题
Our coding style is we pass a pointer to a struct to a function, when we are modifying the contents of the structure.
However, when we are not modifying the contents of a struct, is there still any reason to prefer passing a pointer to a struct to a function?
回答1:
The advantage is in the size being passed: when you pass a large struct, the compiler generates code to make a copy of that struct if you pass it by value. This wastes CPU cycles, and may create a situation when your program runs out of stack space, especially on hardware with scarce resources, such as embedded microcontrollers.
When you pass a struct by pointer, and you know that the function must not make modifications to it, declare the pointer const to enforce this rule:
void take_struct(const struct arg_struct *data) {
data->field = 123; // Triggers an error
}
回答2:
Yes, the pointer's size is usually much smaller than the entire struct's size. You save stack and time.
来源:https://stackoverflow.com/questions/22078053/advantage-of-passing-pointer-to-a-struct-as-argument