zoukankan      html  css  js  c++  java
  • 传入一维数组到函数 Passing 1D array to function

    Since arrays are always passed by reference, all changes made to the array elements inside the function will be made to the original array. 

    int ProcessValues (int [], int ); // works with ANY 1-d array

    Example:

    #include <iostream>
    using namespace std;
    int SumValues (int [], int ); //function prototype
    
    void main( )
    {
      int Array[10]={0,1,2,3,4,5,6,7,8,9};
      int total_sum;
      total_sum = SumValues (Array, 10); //function call
      cout <<”Total sum is “ <<total_sum;
    }
    
    int SumValues (int values[], int num_of_values) //function header
    {
      int sum = 0;
      for( int i=0; i < num_of_values; i++)
        sum+=values[i];
      return sum;
    }

    The only way to protect the elements of the array from being inadvertently changed, is to declare an array to be a const parameter.

    #include <iostream>
    using namespace std;
    int SumValues (const int [], int); //function prototype
    
    int main( )
    {
      const int length =10;
      int Array[10]={0,1,2,3,4,5,6,7,8,9};
      int total_sum;
      total_sum = SumValues (Array, length); //function call
      cout <<”Total sum is “ <<total_sum;
      return 0;
    }
    
    int SumValues (const int values[], int num_of_values) //function header
    {
      int sum = 0;
      for( int i=0; i < num_of_values; i++)
        sum+=values[i];
      return sum;
    }

    Reference:

    http://stackoverflow.com/questions/23035407/passing-1d-and-2d-arrays-by-reference-in-c

    http://doursat.free.fr/docs/CS135_S06/CS135_S06_8_1D_Arrays2.pdf

  • 相关阅读:
    comm---两个文件之间的比较
    fgrep---指定的输入文件中的匹配模式的行
    zip---解压缩文件
    unzip---解压缩“.zip”压缩包。
    tar---打包,解压缩linux的文件和目录
    scp---远程拷贝文件
    make---GNU编译工具
    gcc---C/C++ 编译器
    expr---计算工具
    curl -w 支持的参数
  • 原文地址:https://www.cnblogs.com/learnopencad/p/4314724.html
Copyright © 2011-2022 走看看