Return array from functions in C++

本文介绍如何在C++中通过函数返回整个数组的方法。由于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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值