advantage of passing pointer to a struct as argument?

懵懂的女人 提交于 2021-01-27 05:45:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!