按值将数组传递给函数 [英] Pass an array to a function by value

查看:21
本文介绍了按值将数组传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是C Programming Just the FAQs一书的片段.这是不是因为数组永远不能按值传递?

Below is a snippet from the book C Programming Just the FAQs. Isn't this wrong as Arrays can never be passed by value?

VIII.6:如何将数组按值传递给函数?

答案: 可以通过声明将数组按值传递给函数被调用函数数组名带方括号([])附在最后.当调用函数,只需传递地址数组(即数组的名称)到被调用的函数.例如,以下程序传递数组x[] 到名为的函数byval_func() 按值:

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:

int[] 参数告诉byval_func() 的编译器函数将接受一个参数——一个整数数组.当...的时候byval_func() 函数被调用,你将数组的地址传递给byval_func():

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);

因为数组正在被传递值,数组的精确副本是制作并放置在堆栈上.这被调用的函数然后接收这个数组的副本并可以打印它.因为数组传递给byval_func() 是原始数组,修改数组在 byval_func() 函数中有对原数组没有影响.

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*,它衰减为指针.) 这允许您从被调用的函数中修改数组的内容.因此,这

This is incorrect: the array itself is not being copied, only a copy of the pointer to its address is passed to the callee (placed on the stack). (Regardless of whether you declare the parameter as int[] or int*, it decays into a pointer.) This allows you to modify the contents of the array from within the called function. Thus, this

因为传递给byval_func()的数组是原数组的副本,所以在byval_func()函数内修改数组对原数组没有影响.

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 在下面发表评论).但是,在函数内部重新分配指针并不会改变指向函数外部原始数组的指针.

is plain wrong (kudos to @Jonathan Leffler for his comment below). However, reassigning the pointer inside the function will not change the pointer to the original array outside the function.

这篇关于按值将数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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