Slide 1 of 36

24
Slide 1 of 36

description

Slide 1 of 36. Data type Actual value stored in variable Address of variable Study Programs 9-1 and 9-2 9.1 also uses sizeof function to display number of bytes of storage used. #include using namespace std; int main() { int num; num = 22; - PowerPoint PPT Presentation

Transcript of Slide 1 of 36

Page 1: Slide 1 of 36

                                                                                                                              

                                                      

                                                                                                     Slide 1 of 36

Page 2: Slide 1 of 36

Attributes Associated with Every VariableAttributes Associated with Every Variable

• Data typeData type• Actual value stored in Actual value stored in

variablevariable• Address of variableAddress of variable Study Programs 9-1 Study Programs 9-1

and 9-2and 9-2 9.1 also uses sizeof 9.1 also uses sizeof

function to display function to display number of bytes of number of bytes of storage usedstorage used

#include <iostream>#include <iostream>using namespace std;using namespace std;int main()int main(){{ int num;int num;

num = 22;num = 22; cout << "num = " << num cout << "num = " << num

<< endl; << endl; cout << "The address of cout << "The address of ”” << <<

“ “ num = " num = " << &num << endl;<< &num << endl;

return 0; return 0; }}

Page 3: Slide 1 of 36

Pointers are Variables that Store Pointers are Variables that Store Addresses of Other VariablesAddresses of Other Variables

Pointers must be declared:Pointers must be declared:• Use an indirection operator *Use an indirection operator *• Specify the data type that is pointed toSpecify the data type that is pointed to

Examples:Examples:• int *numAddr;int *numAddr;• float *tabPoint;float *tabPoint;• char *charPoint;char *charPoint;

OS must know OS must know how many bytes how many bytes to set aside for the to set aside for the variable pointed to variable pointed to

The variable pointed to by numAddr is an integer

The variable pointed to by tabPoint is a float

The variable pointed to by charPoint is a character

Page 4: Slide 1 of 36

Which to Use?Which to Use?References or Pointers?References or Pointers?

A reference is a pointer with restricted A reference is a pointer with restricted capabilitiescapabilities• Advantage – hides a lot of internal pointer manipulations Advantage – hides a lot of internal pointer manipulations

from programmerfrom programmer

However, pointers can be added, incremented, and are However, pointers can be added, incremented, and are used by many advanced programmersused by many advanced programmers

Reference NotationReference Notation Pointer NotationPointer Notationint b;int b; int b;int &a = b;int &a = b; int *a = &b;a = 10;a = 10; *a = 10;

(See pnt.cc)(See pnt.cc)

a is a reference variable that stores b’s address. a is not a pointer and can store other values

Page 5: Slide 1 of 36

#include <iostream> // Program 9-3 Page 412using namespace std:int main(){ int *numAddr; // declare a pointer to an int int miles, dist; // declare two integer variables

dist = 158; // store the number 158 into dist miles = 22; // store the number 22 into miles numAddr = &miles; // store the 'address of miles' in numAddr

cout << "\nThe address stored in numAddr is " << numAddr << endl; cout << "The value pointed to by numAddr is " << *numAddr

<< endl;

numAddr = &dist; // now store the address of dist in numAddr cout << "\nThe address now stored in numAddr is " << numAddr

<< endl; cout << "The value now pointed to by numAddr is " << *numAddr

<< endl;

return 0;}

Page 6: Slide 1 of 36

                                                                                                                        

                                                            

                                                      Slide 6 of 36

Page 7: Slide 1 of 36

Saving an addressSaving an address

Addresses may only be stored in variables of Addresses may only be stored in variables of type pointertype pointer

All pointer variables take the same amount of All pointer variables take the same amount of memory, memory, 4 bytes4 bytes in our system in our system

Pointer variables have types: Pointer variables have types: pointer to intpointer to int, , pointer to charpointer to char, etc., etc.

Array namesArray names are (constant) pointers that are (constant) pointers that contain the address of the contain the address of the FIRSTFIRST array array element, Array[0]element, Array[0]

Page 8: Slide 1 of 36

Indirection OperatorIndirection Operator **ptrptr a two-step lookup, i. e. a two-step lookup, i. e.

the variable whose address is stored in ptr the variable whose address is stored in ptr A double lookupA double lookup

• get the value of ptrget the value of ptr• use that value to look up value located in memoryuse that value to look up value located in memory

int normal = 99;int normal = 99;

int *weirdPtr = &normal; int *weirdPtr = &normal;

cout << normal << ‘ ‘ << *weirdPtr;cout << normal << ‘ ‘ << *weirdPtr;

Output

99 99

wierdPtr

cef4normal

99

cef4

Page 9: Slide 1 of 36

More on Declaring PointersMore on Declaring Pointers

int *num1, num2; int *num1, num2; // pointer to an int and an int// pointer to an int and an int int* num1, num2; int* num1, num2; // pointer to an int and an int// pointer to an int and an int int * num1, * num2; // two pointers to intint * num1, * num2; // two pointers to int float* fptr;float* fptr; // pointer to float// pointer to float char * cptr;char * cptr; // pointer to char // pointer to char Type of thing pointed to is used for cin, cout, Type of thing pointed to is used for cin, cout,

arithmetic, and comparisons: arithmetic, and comparisons: cout << *fptr;cout << *fptr;

When used in an expression *fptr is a float, *cptr is a character, and *num1 is an integer

Page 10: Slide 1 of 36

// Pointer version of findMax#include <iostream> using namespace std;main (){ // cin makes more sense hereint n1 = 10, n2 = 5, n3 = 21, n4 = 17, n5 = 33;int* big = &n1; // remember address of n1; n1 is the

//biggest so farif (n2 > *big) // Is 5 > 10? big = &n2; // no changeif (n3 > *big) // Is 21 > 10? big = &n3; // big <- address of n3if (n4 > *big) // Is 17 > 21? big = &n4; // no changeif (n5 > *big) // Is 33 > 21? big = &n5; // big <- address of n5cout << *big << " is biggest.\n";*big = *big * 10; // pointer notation in an expressioncout << *big << " is biggest multiplied by 10.\n";}

Page 11: Slide 1 of 36

Array Names as PointersArray Names as Pointers Every array is implemented with a pointer to the Every array is implemented with a pointer to the

actual data areaactual data area• The pointer is “anonymous” or hiddenThe pointer is “anonymous” or hidden• Array name is a Array name is a constantconstant pointer pointer

Individual element accessIndividual element access• Calculate offset for this element (how many bytes?)Calculate offset for this element (how many bytes?)• Add to address of first elementAdd to address of first element

Treat like any other pointer, except Treat like any other pointer, except constant constant Pointer to an array element can be treated like an Pointer to an array element can be treated like an

array: ptr[index] or use pointer arithmeticarray: ptr[index] or use pointer arithmetic

Page 12: Slide 1 of 36

Two ways to Reference Array Two ways to Reference Array ElementsElements

Array ElementArray Element Subscript Subscript NotationNotation

Pointer Pointer NotationNotation

Element 0Element 0 grade[0]grade[0] *gradePtr*gradePtr

Element 1Element 1 grade[1]grade[1] *(gradePtr +1)*(gradePtr +1)

Element 2Element 2 grade[2]grade[2] *(gradePtr +2)*(gradePtr +2)

Element 3Element 3 grade[3]grade[3] *(gradePtr +3)*(gradePtr +3)

Element 4Element 4 grade[4]grade[4] *(gradePtr +4)*(gradePtr +4)

Page 13: Slide 1 of 36

Program 9-5, a pointer version of 9-4Program 9-5, a pointer version of 9-4See pages 419 - 422See pages 419 - 422

// Program 9-5 - pointer access to an array// Program 9-5 - pointer access to an array#include <iostream> using namespace std;#include <iostream> using namespace std;int main()int main(){{

int *gPtr; // declare a pointer to an int *gPtr; // declare a pointer to an intint

const int SIZE = 5;const int SIZE = 5; int i, grade[SIZE] = {98, 87, 92, 79, 85};int i, grade[SIZE] = {98, 87, 92, 79, 85}; gPtr = &grade[0]; // store 1gPtr = &grade[0]; // store 1stst element address element address for (i = 0; i < SIZE; i++)for (i = 0; i < SIZE; i++) cout cout << "Element " << i << " is " << "Element " << i << " is "

<< *(gPtr + i) << endl;<< *(gPtr + i) << endl; return 0;return 0;}}

Page 14: Slide 1 of 36

Program 9 - 6Program 9 - 6 // Since array name is CONSTANT // Since array name is CONSTANT pointer, // just use array name with pointer, // just use array name with pointer notationpointer notation

#include <iostream> using namespace std;#include <iostream> using namespace std;int main()int main(){{ const int SIZE = 5;const int SIZE = 5; int i, int i, gradegrade[SIZE] = {98, 87, 92, 79, 85};[SIZE] = {98, 87, 92, 79, 85};

for (i = 0; i < SIZE; i++)for (i = 0; i < SIZE; i++) cout << "Element " << i << " is " cout << "Element " << i << " is "

<< *(<< *(gradegrade + i) << endl; + i) << endl;

return 0;return 0;} }

Page 15: Slide 1 of 36

                                                                                                                              

                                                      

                                                      Slide 21 of 36

Page 16: Slide 1 of 36

Pointers: What’s the Point?Pointers: What’s the Point?

Used extensively with stringsUsed extensively with strings Used for call-by-referenceUsed for call-by-reference Early form of generic variablesEarly form of generic variables

• Since pointers are all the same size, a pointer Since pointers are all the same size, a pointer variable is capable of pointing to any data typevariable is capable of pointing to any data type

Allows the programmer to keep track of Allows the programmer to keep track of dynamically allocated memorydynamically allocated memory

• Used extensively in Data Structures courseUsed extensively in Data Structures course

Page 17: Slide 1 of 36

Memory ManagementMemory Management

Most of the variables we have used have been Most of the variables we have used have been automaticautomatic, , i. e., they are allocated memory when the function begins i. e., they are allocated memory when the function begins and destroyed when it ends (Includes globals)and destroyed when it ends (Includes globals)• This allocation uses the program This allocation uses the program stackstack – a temporary location – a temporary location

StaticStatic variables remain allocated and retain value. They variables remain allocated and retain value. They are placed in the (permanent) are placed in the (permanent) heapheap..

DynamicallyDynamically allocated memory comes from the allocated memory comes from the heapheap• newnew obtains a block of storage obtains a block of storage• deletedelete returns it for later use returns it for later use

Program 9-7 is an example of new and delete. Program 9-7 is an example of new and delete. Linked lists, Section 3 - Chapter 11, is better exampleLinked lists, Section 3 - Chapter 11, is better example

Page 18: Slide 1 of 36

                                                                                                                              

                                                      

                                                      Slide 25 of 36

Page 19: Slide 1 of 36

                                                                                                                              

                                                      

                                                      Slide 30 of 36

3 4

Page 20: Slide 1 of 36

                                                                                                                              

                                                      

                                                      Slide 28 of 36

Page 21: Slide 1 of 36

Increments are Scaled when used Increments are Scaled when used with Pointerswith Pointers

If ptr is a pointer to an integer…If ptr is a pointer to an integer…• ptr++ causes the pointer to point to the next integerptr++ causes the pointer to point to the next integer• ptr-- causes the pointer to point to the previous integerptr-- causes the pointer to point to the previous integer• ptr++ or ptr-- actually moves four bytesptr++ or ptr-- actually moves four bytes

If ptr is a pointer to a double…If ptr is a pointer to a double…• ptr++ causes the pointer to point to the next doubleptr++ causes the pointer to point to the next double• ptr-- causes the pointer to point to the previous doubleptr-- causes the pointer to point to the previous double• ptr++ or ptr-- actually moves eight bytesptr++ or ptr-- actually moves eight bytes

If ptr is a pointer to a character…If ptr is a pointer to a character…• ptr++ or ptr-- moves ONE byteptr++ or ptr-- moves ONE byte

Page 22: Slide 1 of 36

                                                                                                                              

                                                      

                                                      Slide 31 of 36

Page 23: Slide 1 of 36

KNOW THIS! Pointers behave KNOW THIS! Pointers behave differently with numbers than with differently with numbers than with

character arrayscharacter arrays/* Pointers to numbers vs. /* Pointers to numbers vs. */*//* Pointers to character strings /* Pointers to character strings */*//* What is accessed or displayed? /* What is accessed or displayed? */*//* /* */*//* Pointer to With * Without * /* Pointer to With * Without * */*//* /* */*//* int/float int/float address /* int/float int/float address */*//* /* */*//* char char BYTE string from there/* char char BYTE string from there */*/

Look at numsVSchars.ccLook at numsVSchars.cc

Page 24: Slide 1 of 36

Common ErrorsCommon Errors

int location = &num; int location = &num; // location is not a pointer variable, no*// location is not a pointer variable, no*

(Use descriptive variable names: numAddr, fPtr, chPtr, ptr…)(Use descriptive variable names: numAddr, fPtr, chPtr, ptr…)

Int * ptr1, ptr2;Int * ptr1, ptr2; // without *, ptr2 is not a pointer// without *, ptr2 is not a pointer

int nums[3], *ptr;int nums[3], *ptr;

Use Use ptrptr = nums;= nums; or or ptr = &nums[0];ptr = &nums[0];

NOT NOT ptr = &nums; ptr = &nums; // nums is already a const pointer// nums is already a const pointer

int *ptr = &99;int *ptr = &99; // can’t take address of literal// can’t take address of literal

Int *ptr = &(diameter * PI); Int *ptr = &(diameter * PI); // nor of an expression// nor of an expression