Return array from functions in C + +

Source: Internet
Author: User

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 has to declare a function returning a pointer a s in the following example:

int* myFunction(){

.

.

.

}

Second point to remember are that C + + does not advocate to return the address of a local variable to outside of the Functio n so you would has to define the local variable as? staticvariable.

Now, consider the following function, which'll generate random numbers and return them using an array and call this F Unction as follows:

#include<iostream>

#include<ctime>

?

Usingnamespace std;

?

function to generate and retrun random numbers.

int* getrandom(){

Staticint r[ten];

?

Set the seed

Srand ((unsigned)time( NULL ) );

?????

for ( int I = 0 ; I < 10 ; ++ i Span style= "COLOR: #666600" >) {

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 Span style= "COLOR: #666600" ><< ;

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

}

?

return0;

}

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

Return array from functions in C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.