将指向结构的指针作为参数传递的优势? [英] advantage of passing pointer to a struct as argument?

查看:41
本文介绍了将指向结构的指针作为参数传递的优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的编码风格是,当我们修改结构的内容时,我们将指向结构的指针传递给函数.

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?

推荐答案

优点在于传递的大小:当你传递一个大的 struct 时,编译器会生成代码来复制它struct 如果按值传递.这会浪费 CPU 周期,并且可能会导致您的程序耗尽堆栈空间,尤其是在资源稀缺的硬件(例如嵌入式微控制器)上.

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.

当你通过指针传递一个 struct 并且你知道函数不能修改它时,声明指针 const 来强制执行这个规则:

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
}

这篇关于将指向结构的指针作为参数传递的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆