gpt4 book ai didi

C编程: the cost of passing by value

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:02 25 4
gpt4 key购买 nike

我正在学习 C 并且对我在网上阅读的内容感到困惑。

http://www.cs.bu.edu/teaching/c/stack/array/

我可以阅读:

Let's look at the functions that determine emptiness and fullness. Now, it's not necessary to pass a stack by reference to these functions, since they do not change the stack. So, we could prototype them as:

int StackIsEmpty(stackT stack);
int StackIsFull(stackT stack);

However, then some of the stack functions would take pointers (e.g., we need them for StackInit(), etc.) and some would not. It is more consistent to just pass stacks by reference (with a pointer) all the time

(我没有展示 stackT 是什么的代码,它只是一个动态数组)

据我(可能是有限的)理解,按值传递的缺点是数据在函数的堆栈内存中重复。由于 stackT 可能很大,通过值而不是指针传递会很耗时。

我做对了吗?还是我对基础知识还不太清楚?

最佳答案

正确,如果您按值传递“大”的东西,该项目将被复制到堆栈上。

指针传递给数据可以避免复制。

性能差异在大多数实际应用程序中是否有意义值得怀疑,除非“大”实际上是“巨大”(这反过来可能会溢出堆栈)。

关于C编程: the cost of passing by value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19671559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com