<<< Pointer as function parameter | Index | Why use pointers? >>> |
Pointer is very similar to a normal integer variable:
#include <iostream> using namespace std; // function declarations void process_zipcodes( int * zip_codes, int size ); int main() { //------------------------------------------------------------- // (a) we can find out how far apart our objects are in memory //------------------------------------------------------------- double car_price = 17000.00; double milk_price = 3.76; double * ptr1 = &car_price; double * ptr2 = &milk_price; // Units of measurement - one double - not one byte! int distance = ptr1 - ptr2; cout << "Distance between two double variables in memory is " << distance << '\n'; //-------------------------------------------------------------------- // (b) we can use simple arithmetic operations to move pointer around //-------------------------------------------------------------------- int * zip_codes = new int[ 5 ]; /* | zip_codes[0] zip_codes[1] zip_codes[2] zip_codes[3] zip_codes[4] | ?????_______ ?????_______ ?????_______ ?????_______ ?????_______ */ zip_codes[ 0 ] = 2184; zip_codes[ 1 ] = 90210; zip_codes[ 2 ] = 12345; zip_codes[ 3 ] = 54321; zip_codes[ 4 ] = 77889; /* *zip_codes | zip_codes[0] zip_codes[1] zip_codes[2] zip_codes[3] zip_codes[4] | 02184_______ 90210_______ 12345_______ 54321_______ 77889_______ */ ++zip_codes; cout << *zip_codes << '\n'; /* *zip_codes | zip_codes[-1] zip_codes[0] zip_codes[1] zip_codes[2] zip_codes[3] | 02184_______ 90210_______ 12345_______ 54321_______ 77889_______ */ zip_codes = zip_codes + 2; /* *zip_codes | zip_codes[-3] zip_codes[-2] zip_codes[-1] zip_codes[0] zip_codes[1] | 02184_______ 90210_______ 12345_______ 54321_______ 77889_______ */ cout << *zip_codes << '\n'; cout << zip_codes[ -3 ] << '\n'; //-------------------------------------------------------------------- // (c) we can pass information to a function via pointer //-------------------------------------------------------------------- process_zipcodes( zip_codes, 2 ); /* *zip_codes | zip_codes[-3] zip_codes[-2] zip_codes[-1] zip_codes[0] zip_codes[1] | 02184_______ 90210_______ 12345_______ 77889_______ 77889_______ */ cout << zip_codes[ 0 ] << '\n'; cout << zip_codes[ 1 ] << '\n'; process_zipcodes( zip_codes - 3, 5 ); return 0; } void process_zipcodes( int * zip_codes, int size ) { cout << "\t Inside process_zipcodes()\n"; cout << *zip_codes << '\n'; cout << zip_codes[ -3 ] << '\n'; *zip_codes = zip_codes[ 1 ]; cout << "\t Exiting process_zipcodes()\n"; }
<<< Pointer as function parameter | Index | Why use pointers? >>> |