Programming for EngineersII - Lec02

Embed Size (px)

Citation preview

  • 8/9/2019 Programming for EngineersII - Lec02

    1/17

    Programming for Engineers - IILecture 02 : Pointers

    by

    Mati Ullah Khan

  • 8/9/2019 Programming for EngineersII - Lec02

    2/17

    Introduction

    You have learned pass by reference

    Pointers also enable pass-by-reference

    Powerful, but difficult to master

    Use of pointers with classes will be discussedlater on in the course

  • 8/9/2019 Programming for EngineersII - Lec02

    3/17

    Pointer Variable Declarations and

    Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct

    reference)

    Pointers contain the address of a variable that has aspecific value (indirect reference) Indirection

    Referencing a pointer value Pointer declarations

    * indicates variable is a pointerint *myPtr;

    declares a pointer to an int, a pointer of type int * Multiple pointers require multiple asterisks

    int *myPtr1, *myPtr2;

    count

    7

    countPtr

    count

    7

  • 8/9/2019 Programming for EngineersII - Lec02

    4/17

    Pointer Variable Declarations andInitialization Can declare pointers to any data type

    Pointers initialization Initialized to 0,NULL, or an address

    0 orNULL points to nothing

  • 8/9/2019 Programming for EngineersII - Lec02

    5/17

    Pointer Operators * (indirection/dereferencing operator) Returns the value of what its operand points to *yPtr returns y (because yPtr points to y).

    *can be used to assign a value to a location in

    memory*yptr = 7; // changes y to 7

    Dereferenced pointer (operand of*) must be anlvalue (no constants)

    * and & are inverses Cancel each other out

    *&myVar == myVar

    and&*yPtr == yPtr

  • 8/9/2019 Programming for EngineersII - Lec02

    6/17

    1 // Fig. 5.4: fig05_04.cpp

    2 // Using the & and * operators

    3 #include45 using std::cout;

    6 using std::endl;

    78 intmain()

    9 {

    10 int a; // a is an integer

    11 int *aPtr; // aPtr is a pointer to an integer

    1213 a = 7;

    14 aPtr = &a; // aPtr set to address of a

    1516 cout

  • 8/9/2019 Programming for EngineersII - Lec02

    7/17

    Calling Functions by Reference

    Call by reference with pointer arguments Pass address of argument using & operator Allows you to change actual location in memory Arrays are not passed with &because the array name is

    already a pointer * operator used as alias/nickname for variable inside

    of functionvoid doubleNum( int *number ){

    *number = 2 * ( *number );}

    *number used as nickname for the variable passed in When the function is called, must be passed an

    addressdoubleNum( &myNum );

  • 8/9/2019 Programming for EngineersII - Lec02

    8/17

    1 // Fig. 5.7: fig05_07.cpp

    2 // Cube a variable using call-by-reference

    3 // with a pointer argument

    4 #include5

    6 using std::cout;

    7 using std::endl;

    8

    9 voidcubeByReference( int * ); // prototype

    10

    11 intmain()

    12 {13 int number = 5;

    14

    15 cout

  • 8/9/2019 Programming for EngineersII - Lec02

    9/17

    Using the Const Qualifier with Pointers

    const qualifier Variable cannot be changed const used when function does not need to change a

    variable Attempting to change a constvariable is a compiler error

    const pointers Point to same memory location Must be initialized when declared

    int *const myPtr = &x; Constant pointer to a non-constant int

    const int *myPtr = &x; Non-constant pointer to a constant int

    const int *const Ptr = &x; Constant pointer to a constant int

  • 8/9/2019 Programming for EngineersII - Lec02

    10/17

    1 // Fig. 5.13: fig05_13.cpp

    2 // Attempting to modify a constant pointer to

    3 // non-constant data

    4 #include

    5

    6 intmain()

    7 {

    8 int x, y;

    9

    10 int * constptr = &x; // ptr is a constant pointer to an

    11 // integer. An integer can be modified

    12 // through ptr, but ptr always points

    13 // to the same memory location.

    14 *ptr = 7;

    15 ptr = &y;

    16

    17 return 0;

    18 }

    Error E2024 Fig05_13.cpp 15: Cannot modify a const object in function main()

    Changing *ptr is allowed - x is not

    a constant.

    Changingptr is an error -ptr is

    a constant pointer.

  • 8/9/2019 Programming for EngineersII - Lec02

    11/17

    Pointer Expressions and Pointer

    Arithmetic Pointer arithmetic

    Increment/decrement pointer (++ or --) Add/subtract an integer to/from a pointer( + or += , -

    or-=

    )

    Pointers may be subtracted from each other Pointer arithmetic is meaningless unless performed on

    an array

    5 element int array on a machine using 4 byte intsvPtr points to first elementv[ 0 ], which is at

    location 3000vPtr = 3000

    vPtr += 2; setsvPtr to 3008vPtr points tov[ 2 ]

    pointer variablevPtr

    v[0] v[1] v[2] v[4]v[3]

    3000 3004 3008 3012 3016

    location

  • 8/9/2019 Programming for EngineersII - Lec02

    12/17

    Pointer Expressions and Pointer

    Arithmetic Subtracting pointers

    Returns the number of elements between twoaddresses

    vPtr2 = v[ 2 ];vPtr = v[ 0 ];vPtr2 - vPtr == 2

    Pointer comparison

    Test which pointer points to the higher numberedarray element

    Test if a pointer points to 0 (NULL)if ( vPtr == 0 )

    statement

  • 8/9/2019 Programming for EngineersII - Lec02

    13/17

    Pointer Expressions and Pointer

    Arithmetic Pointers assignment

    If not the same type, a cast operator must be used

    Exception: pointer tovoid(typevoid *) Generic pointer, represents any type

    No casting needed to convert a pointer tovoidpointer

    voidpointers cannot be dereferenced

  • 8/9/2019 Programming for EngineersII - Lec02

    14/17

    The Relationship Between Pointers and

    Arrays Arrays and pointers closely related

    Array name like constant pointer

    Pointers can do array subscripting operations Having declared an arrayb[ 5 ] and a pointerbPtr

    bPtr is equal tob

    bptr == b

    bptr is equal to the address of the first element ofb

    bptr == &b[ 0 ]

  • 8/9/2019 Programming for EngineersII - Lec02

    15/17

    The Relationship Between Pointers and

    Arrays Accessing array elements with pointers Elementb[ n ] can be accessed by *( bPtr +n ) Called pointer/offset notation

    Array itself can use pointer arithmetic.b[ 3 ] same as *(b + 3)

    Pointers can be subscripted (pointer/subscript

    notation)bPtr[ 3 ] same asb[ 3 ]

  • 8/9/2019 Programming for EngineersII - Lec02

    16/17

    Arrays of Pointers

    Arrays can contain pointers Commonly used to store an array of strings

    char *suit[ 4 ] = {"Hearts", "Diamonds","Clubs", "Spades" };

    Each element of suit is a pointer to a char * (a string) The strings are not in the array, only pointers to the

    strings are in the array

    suit array has a fixed size, but strings can be of anysize

    suit[3]

    suit[2]

    suit[1]

    suit[0] H e a r t s \0

    D i a m o n d s \0

    C l u b s \0

    S p a d e s \0

  • 8/9/2019 Programming for EngineersII - Lec02

    17/17

    Questions???