传递整个数组给函数 [英] Passing whole array to a function

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

问题描述

当我们传递一个数组的元素给一个函数,它被视为一个正常的变量和调用的函数创建实参的副本,并在其上​​运行。在正式的参数所做的任何更改不会影响实际参数。

When we pass an element of an array to a function, it is treated as an normal variable and the called function creates a copy of the actual argument and operates on it. Any changes made in the formal arguments doesn't affect the actual arguments.

但是,这不,当我们传递一个整个阵列的情况。在这种情况下,它(调用函数)获得进入实际参数和形式参数所做的任何更改将影响实际的参数。为什么出现这种情况?

But this not the case when we pass a whole array. In this case it (called function) gets access to the actual arguments and any changes made in the formal arguments affects the actual arguments. Why this happens?

推荐答案

该数组的指针的元素通过。

The array is passed as a pointer to the elements.

如果我写的:

void doStuff(int *ptr)
{
  ptr[1] = 5;
}

int main()
{
  int arr[] = {0, 1, 2};
  doStuff(arr);
  printf("%d %d %d\n", arr[0], arr[1], arr[2]);
}

的输出将是0 5 2。这是因为C已通过任何实际上是值的参数。该参数是一个指向一个int。因此,一个指向一个int是按值传递。因此,doStuff得到一个指针的一个拷贝到存储在主的堆栈帧。当它与解除引用 PTR [1] ,它是继指针主存储器和修改数组有没有指针。

the output will be "0 5 2". That's because C passes whatever is actually the parameter by value. The parameter is a pointer to an int. So a pointer to an int is passed by value. Thus, doStuff gets a copy of a pointer to memory in main's stack frame. When it dereferences that pointer with ptr[1], it is following the pointer to main's memory and modifying the array there.

而C只能按值传递,但它这样做浅。如果你问它传递一个int *,它会通过一个int *。它仅复制指针的值,而不是任何事物的价值指向。

C can only pass by value, but it does so "shallowly". If you ask it to pass an int *, it will pass an int *. It only copies the value of the pointer, not the values of anything it points to.

如果你想doStuff得到自己的数组的副本,无论是包装在一个结构数组作为其他人所说,或者使用的memcpy手动深拷贝数组是这样的:

If you want doStuff to get its own copy of the array, either wrap the array in a struct as others have suggested, or use memcpy to manually deep copy the array like this:

void doStuff(int *ptr, int nElems)
{
  int myCopyOfTheArray[nElems];
  memcpy(myCopyOfTheArray, ptr, sizeof(int) * nElems);
  /* do stuff with the local copy */
}

与使用结构中,memcpy的方式工作,如果nElems只知道在运行时。

Unlike using a struct, the memcpy approach works if nElems is only know at runtime.

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

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