using namespace std;
#include<iostream>
int passarr(int b[],int s)
{
//Some Modification in the array b
b[0]=0;
b[s-1]=0;
//Printing the array b
for(int i=0;i<s;i++)
{
cout<<b[i]<<" ";
}
cout<<endl;
}
int main()
{
int arr[100];
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
//Function call and passing array a to the function`
passarr(arr,n);
//Printing the array arr
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}
在这段代码中,我将数组 arr
传递给函数 passarr()
,它执行一些修改。问题是修改也会反射(reflect)在原始数组上。有什么方法可以将数组传递给函数,以便在函数中执行任何操作时不会更改原始数组?
最佳答案
Is there any way to pass the array to a function so that the original array does not get changed while performing any operation in the function?
我能想到的选择:
在函数中复制数组并修改拷贝。保持输入数组不变。
按值传递
std::vector
。对参数的任何更改都不会影响调用函数中的对象。如果您在编译时知道数组的大小,请按值传递
std::array
。对参数的任何更改都不会影响调用函数中的对象。
关于c++ - 如何将数组传递给函数,以便在更改该函数中的数组值时原始数组的值不会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101476/