In the previous chapters, we have read about both the topics of pointers as well as the functions in C++. But in this chapter, we are going to learn how these two concepts can be used with one another in C++. Both these topics are of utmost importance and are really fun to use. So let us take a look at them in detail.

Passing pointers to functions:

C++ allows the coder to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.

#include <iostream.h>

#include <ctime.h>

void gS(unsigned long *par); //function declaration

int main () {

   unsigned long sec;

   gS( &sec );

   // print the actual value

   cout << "Number of seconds :" << sec << endl;

   return 0;

}

void gS(unsigned long *par) { //function definition

   // get the current number of seconds

   *par = time( NULL );

}

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

Number of seconds: 1294450

In the above example, we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function.

 

Return Pointers from Functions:

C++ also allows the feature to return pointers from the functions. For this purpose, we use the following 

Syntax:

int *Func_name() {

   .

   .

   .

}

Note: Here we are returning an integer value because, pointers are actually addresses, which are actually numbers themselves.

#include <iostream.h>

#include <ctime.h>

// function to generate and retrun random numbers.

int * getRandom( ) {

   static int  r[5];

 // set the seed

   srand( (unsigned)time( NULL ) );

   

   for (int i = 0; i < 5; ++i) {

      r[i] = rand();

      cout << r[i] << endl;

   }

    return r;

}

 // main function to call above defined function.

int main () {

   // a pointer to an int.

   int *p;

    p = getRandom();

   for ( int i = 0; i < 5; i++ ) {

      cout << "*(p + " << i << ") : ";

      cout << *(p + i) << endl;

   }

    return 0;

}

Output:

672723198

9998735695

804513585

971235677

618989504


*(p + 0): 672723198

*(p + 1): 9998735695

*(p + 2): 804513585

*(p + 3): 971235677

*(p + 4): 618989504

 

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019