Easy Tutorial
❮ C Function Strspn C Exercise Example16 ❯

Returning Pointers from Functions in C

C Pointers

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

int * myFunction()
{
.
.
.
}

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

Now, let's look at the following function, which generates 10 random numbers and returns them using the array name (which is 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;
}

/* Main function to call the above defined function */
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 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 Pointers

❮ C Function Strspn C Exercise Example16 ❯