传递数组由值的函数 [英] Pass an array to a function by value

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

问题描述

下面是书中的 C程序设计就在常见问题解答的一个片段。这是不是错了,因为数组不能按引用传递?


  

VIII.6:你怎么能按值传递数组给一个函数


  
  

答:数组可以按值声明中传递给函数
  调用的函数数组名
  用方括号( []
  附连到端。调用当
  功能,只需通过地址
  的阵列(即,阵列的名字)
  到被调用的功能。例如,
  以下程序通过阵列
   X [] 给函数命名
   byval_func()按值:


  
  

INT [] 参数告诉
  编译器的 byval_func()
  功能将一个参数,一个
  整型数组。当。。。的时候
   byval_func()函数被调用,你
  通过该阵列的该地址
   byval_func()

  byval_func(X);

由于该阵列是由传递
  值,数组的精确副本
  提出并放置在堆栈中。该
  调用的函数然后接收这
  阵列的复制和可以打印。
  由于数组传递给
   byval_func()是一个副本
  原数组,修改数组
  在 byval_func()函数
  原始阵列上没有影响



解决方案

  

由于该数组是由值传递,数组的精确副本,是由并放置在堆栈中。


这是不正确的:阵列本身不被抄袭,只是一个指针,它的地址副本被传递到被叫方(放置在栈上)。 (不管你是否声明参数为 INT [] 为int * ,它的decays成一个指针。)这允许你从被调用函数中修改数组的内容。因此,本


  

由于传递给byval_func()数组是原始数组的拷贝,修改阵列byval_func内()函数的原始阵列上没有影响


是完全错误的(荣誉给@乔纳森莱弗勒低于他的意见)。然而,重新分配函数内部的指针不会指针更改为功能外原始数组。

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

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.

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

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.

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天全站免登陆