gpt4 book ai didi

c - 按值将数组传递给函数

转载 作者:太空狗 更新时间:2023-10-29 16:20:49 25 4
gpt4 key购买 nike

下面是C Programming Just the FAQs一书的片段。这不是错误的吗,因为数组永远不能按值传递?

VIII.6: How can you pass an array to a function by value?

Answer: An array can be passed to a function by value by declaring in the called function the array name with square brackets ([ and ]) attached to the end. When calling the function, simply pass the address of the array (that is, the array’s name) to the called function. For instance, the following program passes the array x[] to the function named byval_func() by value:

The int[] parameter tells the compiler that the byval_func() function will take one argument—an array of integers. When the byval_func() function is called, you pass the address of the array to byval_func():

byval_func(x);

Because the array is being passed by value, an exact copy of the array is made and placed on the stack. The called function then receives this copy of the array and can print it. Because the array passed to byval_func() is a copy of the original array, modifying the array within the byval_func() function has no effect on the original array.

最佳答案

Because the array is being passed by value, an exact copy of the array is made and placed on the stack.

这是不正确的:数组本身没有被复制,只有指向其地址的指针的副本被传递给被调用者(放在堆栈上)。 (无论您将参数声明为 int[] 还是 int*,它都是 decays into a pointer。)这允许您修改数组的内容在被调用函数中。因此,这

Because the array passed to byval_func() is a copy of the original array, modifying the array within the byval_func() function has no effect on the original array.

完全错误(感谢@Jonathan Leffler 在下面的评论)。但是,在函数内部重新分配指针不会改变函数外部指向原始数组的指针。

关于c - 按值将数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774456/

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