Download presentation
Presentation is loading. Please wait.
1
Pointers 1 Pointers Pointers In chapter three we looked at passing parameters to functions using call by value, and using call by reference, using reference variables (&x) We can also pass parameters using pointer variables to simulate call by reference and to pass dynamic data structures (data structures that grow and shrink during runtime). Pointer variable declaration and initialization: int y=5; int *yPtr; yPtr = &y; cout << *yPtr; cout << y; *yPtr = 9; cin >> *yPtr Pointers need to be initialized when they are declared, or in an assignment statement. A pointer may be initialized to 0, NULL, or an address. In C++ style, 0 seems to be preferable to NULL.
2
Pointers 2 #include #include using std::cout;using std::endl; int main ( ) { int a = 7, *aPtr = &a; cout << “The address of a is “ << &a << “\nThe value of aPtr is “ << aPtr; cout << “\n\nThe value of a is “ << a << “\nThe value of *aPtr is “ << *aPtr; cout << “\n\nShowing that * and & are inverses of “ << “each other.\n&*aPtr = “ << &*aPtr << “\n*&aPtr = “ << *&aPtr << endl; return 0 }Output: The address of a is 006AFDF4 The value of aPtr is 006AFDF4 The value if a is 7 The value of *aPtr is 7 Showing that * and & are inverses of each other. &*aPtr = 006AFDF4 *&aPtr = 006AFDF4
3
Pointers 3 Passing by value vs. passing by reference using pointers Passing by value vs. passing by reference using pointers //Cube by value #include #include using std::cout; using std::endl; int cubeByValue( int ); int main ( ) { int number = 5; cout << “The original value of number is “ << number; number = cubeByValue( number ); cout << “\nThe new value of number is “ << number << endl; return 0; } int cubeByValue( int n ) { return n * n * n; }
4
Pointers 4 //Cube by reference using a pointer variable #include #include using std::cout; using std::endl; void cubeByReference( int * ); int main ( ) { int number = 5; cout << “The original value of number is “ << number; cubeByReference ( &number ); cout << “\nThe new value of number is “ << number << endl; return 0; } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; }
5
Pointers 5 The relationship between Pointers and Arrays The relationship between Pointers and Arrays int b [ 5 ], *bptr = b; bptr == &b [ 0 ] *( bptr + 3 ) == b[ 3 ] &b[ 3 ] == bptr + 3 *( b + 3 ) == b [ 3 ] bptr[ 1 ] == b[ 1 ] An array name is a constant pointer, so b += 3 is invalid.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.