Pointers to parameters to functions
We have seen how declaring a reference in the function argument lets us change the variable inside the function. Pointers also allow for doing something similar.
Ex:
File: param1.cpp
#include<stdio.h> int global1 = 300 ; //--------------------------------------------------------------------------------------------------- void swap3( int** param1 ) { *param1 = &global1 ; } //--------------------------------------------------------------------------------------------------- void swap2( int* param1 ) { *param1 = 200 ; } //--------------------------------------------------------------------------------------------------- void swap1( int param1 ) { param1 = 200 ; } //--------------------------------------------------------------------------------------------------- int main() { int x1 = 100 ; int* ptr1 ; int** doublePointer ; printf("%d\n" , x1 ); swap1( x1 ) ; printf("%d\n" , x1 ); ptr1 = &x1 ; swap2( &x1 ) ; printf("%d\n" , x1 ); //Change the value of a pointer. doublePointer = &ptr1 ; swap3( doublePointer ) ; printf("%d\n" , **doublePointer ); printf("%d\n" , *ptr1 ); return(0) ; }
/* RAM global1 0 300 x1 1 100 2 3 ptr1 4 1 -> 0 ptr2 100 4 */In the above program we have declared three functions "swap1" , "swap2" and "swap3" . The function "swap1" shows that if we pass an integer from the main function to the function "swap1" it's value in the main function does not get changed since we are passing by value. In the function "swap2" we pass the address of the variable "x1" and the function swap2 takes a pointer as it's argument. Using the pointer it changes the value of x1. The last function "swap3" changes the value of the pointer ptr1 by making it point to the address of "global1" instead of "x1" . To change the value of an integer we passed in it's address. To change the value of a pointer "ptr1" we take the address of "ptr1" and that makes it a double pointer. The argument to the function "swap3" is a double pointer.