Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Returning a Pointer from a Function

C++ Returning a Pointer from a Function

C++ Pointers C++ Pointers

In the previous chapter, we learned how to return an array from a function in C++. Similarly, C++ allows you to return a pointer from a function. To do this, you must declare a function that returns a pointer, as shown below:


int * myFunction()
{
.
.
.
}

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

Now, let us look at the function below, which generates 10 random numbers and returns them using the array name (that is, the address of the first array element), which represents a pointer, as follows:

Example

#include

#include

#include

 

using

namespace

std

;

 

// Function to generate and return 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 the function defined above

int

main

(

)

{

   

// A pointer to an integer

   

int

p

;

 

   p

=

getRandom

(

)

;

   

for

(

int

i

=

0

;

i

<

10

;

i

++

)

   

{

       

cout

<<

"*(p + "

<<

i

<<

") : "

;

       

cout

<<

(

p

i

)

<<

endl

;

   

}

 

   

return

0

;

}

When the code above is compiled and executed, it produces the following result:


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

C++ Pointers C++ Pointers