Cpp - Pointers As Parameters

Introduction

To declare a function parameter to allow an address to be passed to the function as an argument, use a pointer variable.

The function func() requires the address of an int value as an argument:

long func( int *iPtr ) 
{ 
    // Function block 
} 

to declare the parameter iPtr as an int pointer.

In the following code the function swap() swaps the values of the variables x and y in the calling function.

The function swap() is able to access the variables since the addresses of these variables, that is &x and &y, are passed to it as arguments.

The parameters p1 and p2 in swap() are thus declared as float pointers. The statement

swap( &x, &y); 

initializes the pointers p1 and p2 with the addresses of x or y.

When the function manipulates the expressions *p1 and *p2, it really accesses the variables x and y in the calling function and exchanges their values.

Demo

// Demonstrates the use of pointers as parameters. 
#include <iostream> 
using namespace std;

void swap(float *, float *);   // Prototype of swap() 

int main()/*from  w  ww . j  a va2 s.  c o m*/
{
  float x = 11.1F;
  float y = 22.2F;
  swap(&x, &y);
  cout << x;
  cout << y;
}

void swap(float *p1, float *p2)
{
  float temp;          // Temporary variable 

  temp = *p1;          // At the above call p1 points 
  *p1 = *p2;          // to x and p2 to y. 
  *p2 = temp;
}

Result

Related Topic