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

C Returning an Array from a Function

C Returning an Array from a Function

C Arrays C Arrays

The C language does not allow returning a complete array as a function argument. However, you can return a pointer to an array by specifying the array name without an index. We will cover pointers in the next chapter; you can skip this chapter for now and come back to it after learning about C pointers.

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

(

)

{

. . .

}

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

Now, let us look at the function below, which generates 10 random numbers and returns them using an array, as follows:

Example

#include

<

stdio.h

#include

<

stdlib.h

#include

<

time.h

/*

A function to generate and return random numbers

*/

int

getRandom

(

)

{

static

int

r

[

10

]

;

int

i

;

/*

Set the seed

*/

srand

(

(

unsigned

)

time

(

NULL

)

)

;

for

(

i

=

0

;

i

<

10

; ++

i

)

{

r

[

i

]

=

rand

(

)

;

printf

(

"

r[%d] = %d

\

n

"

,

i

,

r

[

i

]

)

;

}

return

r

;

}

/*

The main function that calls the function defined above

*/

int

main

(

)

{

/*

A pointer to an integer

*/

int

p

;

int

i

;

p

=

getRandom

(

)

;

for

(

i

=

0

;

i

<

10

;

i

++

)

{

printf

(

"

*(p + %d) : %d

\

n

"

,

i

, *

(

p

i

)

)

;

}

return

0

;

}

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



r[0] = 313959809

r[1] = 1759055877

r[2] = 1113101911

r[3] = 2133832223

r[4] = 2073354073

r[5] = 167288147

r[6] = 1827471542

r[7] = 834791014

r[8] = 1901409888

r[9] = 1990469526

*(p + 0) : 313959809

*(p + 1) : 1759055877

*(p + 2) : 1113101911

*(p + 3) : 2133832223

*(p + 4) : 2073354073

*(p + 5) : 167288147

*(p + 6) : 1827471542

*(p + 7) : 834791014

*(p + 8) : 1901409888

*(p + 9) : 1990469526

C Arrays C Arrays