C Returning a Pointer from a Function
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()
{
.
.
.
}
Also, the C language does not support returning the address of a local variable when calling 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 the array name (that is, the address of the first array element), which represents a pointer, as follows:
Example
#include
<
stdio.h
#include
<
time.h
#include
<
stdlib.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
(
"
%d
\
n
"
,
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:
1523198053
1187214107
1108300978
430494959
1421301276
930971084
123250484
106932140
1604461820
149169022
*(p + [0]) : 1523198053
*(p + [1]) : 1187214107
*(p + [2]) : 1108300978
*(p + [3]) : 430494959
*(p + [4]) : 1421301276
*(p + [5]) : 930971084
*(p + [6]) : 123250484
*(p + [7]) : 106932140
*(p + [8]) : 1604461820
*(p + [9]) : 149169022
C Pointer