150 likes | 257 Views
Variable and Pointer. num. num. 42. 42. A memory location that stores a value “like a box which can store a single int value such as 42”. What is a pointer?. a memory location that stores a reference to another value. What is a variable?. numPtr.
E N D
Variable and Pointer num num 42 42 • A memory location that stores a value • “like a box which can store a single int value such as 42” What is a pointer? • a memory location that stores a referenceto another value. What is a variable? numPtr the variable being pointed to is called “pointee”
Last Week • Variable • Pointer • Pointee • Dereference • Declaring Pointer • Initializing Pointers • Using assignment statement (p = &num) • Using new ( p = new int) • Pointers and Arrays • Accessing Arrays : Pointer and Index
Today • Searching Algorithms • Sequential • Binary
Variable and Pointer num 42 10500 numPtr 10500 42
Pointer Dereference • "dereference" operation follows a pointer's reference to get the value of its pointee. • The value of the dereference of numPtr above is 42 • A pointer must have a pointee • Bugs occur when a pointer has no pointee
num 42 Pointer Assignment 10500 10500 numPtr numPtr2 numPtr2=numPtr 42 Bonus question: What is the value of numPtr2 ?
& and * operator • numPtr = &num // computes reference to num and store it in numPtr • *numPtr gives 42 // (“dereference” numPtr) 10500 10500 int num; int *numPtr; int *numPtr2; num=42; numPtr = # numPtr2=numPtr 42
Initializing a pointer • Use assignment statement and & operator to initialize as in numPtr=&num • Use new
Assignment statement int num; int *numPtr; int *numPtr2; num=42; numPtr = # numPtr2=numPtr
? ? 10500 ? p1 1900 42 ? 10500 The new operator • allocates memory and return a pointer 10500 int *numPtr; numPtr = new int; *numPtr = 42; - p1 points to a dynamic integer variable which comes from the heaps 42
Dynamic Arrays numPtr ? 900 10488 int *numPtr; numPtr= new int[4]; numPtr[2] = 42; cout<<*(numPtr+2); 42 10488 - numPtr points to 1st cell of array 42
Accessing Arrays • Pointer • Array Index Pointer Array numPtr[0]=20 *numPtr=20 numPtr[1]=30 *(numPtr+1)=30
Pointers and Arrays as Parameters • Pointers and Arrays can be passed as parameters to functions
Array/Pointer Parameters void Set50(int memArray[ ], int size) { for (int i = 0 ; i< size; i++) { memArray[i] = 50; } } Calling module int num[40]; Set5-(num, 40); Calling module: int *numPtr; numPtr = new int[40] Set50(numPtr, 30); • numPtr is passed as to the function • memArray is the parameter
Bonus questions: • How do you declare pointers? int *ptr, char *c; • How do you make pointer point to pointee? ptr = new int; char = new char[5]; ptr = #