gpt4 book ai didi

c++ - 按值发送数组作为参数?

转载 作者:行者123 更新时间:2023-11-30 01:09:40 24 4
gpt4 key购买 nike

我做了一个很简单的代码,学习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 的原型(prototype)是

void ByValue(int* arr, int size)

即该数组已退化 为指针类型。因此,对数组的修改反射(reflect)在调用者中。

请注意,符号 *(arr + n)arr[n] 相同

关于c++ - 按值发送数组作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39848383/

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