C + + Returns an array from a function

Source: Internet
Author: User

C + + does not allow the return of a complete array as a function parameter. However, you can return a pointer to an array by specifying an array name without an index.

If you want to return a one-dimensional array from a function, you must declare a function that returns a pointer, as follows:

int * myFunction () {...}

In addition, C + + does not support returning the address of a local variable outside of a function unless the local variable is defined as a static variable.

Now, let's look at the following function, which generates 10 random numbers and uses an array to return them, as follows:

#include <iostream>#include<cstdlib>#include<ctime>using namespacestd;//function to generate and return a random numberint*Getrandom () {Static intr[Ten]; //Set seedSrand ((unsigned) time (NULL));  for(inti =0; I <Ten; ++i) {R[i]=rand (); cout<< R[i] <<Endl; }   returnR;} //to invoke the main function that defines the function aboveintMain () {//a pointer to an integer   int*p; P=Getrandom ();  for(inti =0; I <Ten; i++) {cout<<"* (P +"<< I <<") : "; cout<< * (p + i) <<Endl; }    return 0;}

C + + returns an array from a function

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.