如何在调用后保留数组的原始值?

时间:2017-03-12 03:15:24

标签: c++ arrays

  #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的第二次调用中显示?

1 个答案:

答案 0 :(得分:1)

您不能按值传递数组内容,以便保留原始数据副本所需的原始值,如下面的代码所述:

 #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);
}