C Returning Pointer from Functions

C Pointers

In the previous chapter, we learned how to return arrays from functions 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 language does not support returning the address of a local variable when calling a function, unless the local variable is defined asstaticvariable.

Now, let's look at the following function, which generates 10 random numbers and returns them using the array name that represents the pointer (i.e., the address of the first array element), as follows:

Example

#include <stdio.h> #include <time.h> #include <stdlib.h> /*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 to call 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 above code is compiled and executed, it produces the following results:

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 Pointers

other extensions