Return array from functions in C++

來源:互聯網
上載者:User

標籤:local   win   rda   dimen   rom   function   null   ios   set   

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>

?

usingnamespace std;

?

// function to generate and retrun random numbers.

int* getRandom(){

staticint 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;

}

?

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++

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.