zoukankan      html  css  js  c++  java
  • Return array from functions in C++

    C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

    If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:

    int * myFunction() {

    .

    .

    .

    }

    Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

    Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows:

    #include <iostream>

    #include <ctime>

     

    using namespace std;

     

    // function to generate and retrun random numbers.

    int * getRandom( ) {

    static int r[10];

     

    // set the seed

    srand( (unsigned)time( NULL ) );

          

    for (int i = 0; i < 10; ++i) {

    r[i] = rand();

    cout << r[i] << endl;

    }

     

    return r;

    }

     

    // main function to call above defined function.

    int main () {

    // a pointer to an int.

    int *p;

     

    p = getRandom();

          

    for ( int i = 0; i < 10; i++ ) {

    cout << "*(p + " << i << ") : ";

    cout << *(p + i) << endl;

    }

     

    return 0;

    }

    When the above code is compiled together and executed, it produces result something as follows:

    624723190

    1468735695

    807113585

    976495677

    613357504

    1377296355

    1530315259

    1778906708

    1820354158

    667126415

    *(p + 0) : 624723190

    *(p + 1) : 1468735695

    *(p + 2) : 807113585

    *(p + 3) : 976495677

    *(p + 4) : 613357504

    *(p + 5) : 1377296355

    *(p + 6) : 1530315259

    *(p + 7) : 1778906708

    *(p + 8) : 1820354158

    *(p + 9) : 667126415

  • 相关阅读:
    装饰者模式和适配器模式
    java 中获得 资源文件方法
    在windows 上统计git 代码量
    Linux-静态库生成
    Redis-Redi事务注意事项
    Linux-使用 yum 升级 gcc 到 4.8
    Linux-配置虚拟IP
    PHP-PSR-[0-4]代码规范
    Linux-/etc/rc.local 或 service 中使用 sudo -u xxx cmd 执行失败(sorry, you must have a tty to run sudo)解决办法
    Linux-系统负载
  • 原文地址:https://www.cnblogs.com/time-is-life/p/7221163.html
Copyright © 2011-2022 走看看