gpt4 book ai didi

c++ - 调用后如何保留数组的原始值?

转载 作者:行者123 更新时间:2023-11-28 05:15:29 25 4
gpt4 key购买 nike

  #include <iostream>

using std::cout;
using std::endl;

void staticArrayInit(int[]);

int main()
{
int array2[3]={1,2,3};

cout << "First call to each function:\n";
staticArrayInit(array2);

cout << "\n\nSecond call to each function:\n";
staticArrayInit(array2);
cout << endl;

return 0;

}

void staticArrayInit(int array2[])
{


static int array1[ 3 ];

cout << "\nValues on entering staticArrayInit:\n";

for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = " << array1[ i ] << " ";

cout << "\nValues on exiting staticArrayInit:\n";

for ( int j = 0; j < 3; j++ )
cout << "array1[" << j << "] = "
<< ( array1[ j ] += 5 ) << " ";

cout << "\n\nValues on entering automaticArrayInit:\n";

for ( int i = 0; i < 3; i++ )
cout << "array2[" << i << "] = " << array2[ i ] << " ";

cout << "\nValues on exiting automaticArrayInit:\n";

for ( int j = 0; j < 3; j++ )
cout << "array2[" << j << "] = "
<< (array2[ j ] += array1[j]) << " ";

}

如您所见,staticarrayinit 将被调用两次。第一次调用后,array2 (1,2,3) 的原始值将被修改,在第二次调用中,将显示的值是修改后的值。如何保留 array2 的原始值并在 staticArrayInit 的第二次调用中显示它?

最佳答案

您不能按值传递数组内容,因此要保留原始值,您需要维护原始数组的拷贝,如下面的代码所述:

 #include <iostream>
#include <cstring>
using std::cout;
using std::endl;

void staticArrayInit(int[]);

int main()
{
int array2[3]={1,2,3};

cout << "First call to each function:\n";
staticArrayInit(array2);

cout << "\n\nSecond call to each function:\n";
staticArrayInit(array2);
cout << endl;

return 0;

}

void staticArrayInit(int array2[])
{


static int array1[ 3 ];
int arraycopy[sizeof(array2)];
std::copy(array2,array2+3,arraycopy);
cout << "\nValues on entering staticArrayInit:\n";

for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = " << array1[ i ] << " ";

cout << "\nValues on exiting staticArrayInit:\n";

for ( int j = 0; j < 3; j++ )
cout << "array1[" << j << "] = "
<< ( array1[ j ] += 5 ) << " ";

cout << "\n\nValues on entering automaticArrayInit:\n";

for ( int i = 0; i < 3; i++ )
cout << "array2[" << i << "] = " << array2[ i ] << " ";

cout << "\nValues on exiting automaticArrayInit:\n";

for ( int j = 0; j < 3; j++ )
cout << "array2[" << j << "] = "
<< (array2[ j ] += array1[j]) << " ";
std::copy(arraycopy,arraycopy+3,array2);
}

关于c++ - 调用后如何保留数组的原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743309/

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