按值作为参数发送一个数组?
我做了一个非常简单的代码,学习C++。我发现,当我将堆栈上创建的数组发送到另一个函数时,函数将更改源数组 - 这与其他变量不同。像一个int或其他东西。按值作为参数发送一个数组?
这是为什么?
代码:
void ByValue(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
arr[i] += 1;
}
}
void SimpleArray()
{
int arr[3];
for (int i = 0; i < 3; i++)
{
arr[i] = i+1;
cout << "Element [" << i << "] is " << arr[i] << endl;
}
cout << endl;
ByValue(arr, 3);// <-- should be by value
for (int i = 0; i < 3; i++)
{
cout << "Element after change [" << i << "] is " << arr[i] << endl; // <-- this shouldent change ?
}
cout << endl;
}
给出的输出:
Element [0] is 1
Element [1] is 2
Element [2] is 3
Element after change [0] is 2
Element after change [1] is 3
Element after change [2] is 4
第二输出应是相同的,第一,如果它是由值, 通过,但现在是像我使用的指针?
有效地,原型ByValue
是
void ByValue(int* arr, int size)
即阵列已经衰减到指针类型。所以因此修改数组是反映在调用者中的。
请注意,符号*(arr + n)
是相同到arr[n]
。
注意:参数已经*调整为指针。参数*衰减*因为参数是指针。 – juanchopanza
但数组仍然在堆栈上?那么byValue中的poniter指向堆栈? – Niklas
阵列当然有自动存储时间。指针也可以指向这些类型。 – Bathsheba
将一个数组传递给一个函数会将其衰减为指针。所以实际上正在对原始数组进行更改。 arr只是数组中第一个元素的地址。并且该地址正在传递给该函数。因此,在功能,如果你做
arr[index] = value;
, 它被细分*(arr + index) = value;
这将使您的原始数组为arr
的变化是相同的地址作为原始数组的第一个元素的地址。
使用'std :: array'实现按值传递数组 –