POINTERS Pointers A pointer in C is said

  • Slides: 28
Download presentation
POINTERS

POINTERS

Pointers Ü A pointer in C++ is said to "point to" the memory address

Pointers Ü A pointer in C++ is said to "point to" the memory address that is stored in it. Ü Also, when defining a C++ pointer variable, we must specify the type of variable to which it is pointing. //Sample program for c++ pointer void main() { int* p; }

0 1 2 3 4 5 81346 81347 123 . . . j =

0 1 2 3 4 5 81346 81347 123 . . . j = 123; x = &j; x Address MEMORY . . . A pointer is a variable that holds the address of j something else. int j; int *x; 3

int *x; Üx is a pointer to an integer. ÜYou can use the integer

int *x; Üx is a pointer to an integer. ÜYou can use the integer x points to in a C++ expression like this: “the int x points to” y = *x + 17; *x = *x +1;

Assigning a value to a dereferenced pointer A pointer must have a value before

Assigning a value to a dereferenced pointer A pointer must have a value before you can dereference it (follow the pointer). int *x; *x=3; R!!! O R R oint E p t ’ n s x doe !!! ing h t y n to a int j; int *x; x = &j; *x=3; ine f s i this to j s t n i x po

Pointers to anything x int *x; int **y; y double *z; some *int z

Pointers to anything x int *x; int **y; y double *z; some *int z some int some double

Pointers and Arrays ÜAn array name is basically a const pointer. ÜYou can use

Pointers and Arrays ÜAn array name is basically a const pointer. ÜYou can use the [ ] operator with a pointer: x is “the address of a[2] ” int *x; int a[10]; x = &a[2]; x[i] is the same as a[i+2] for (int i=0; i<3; i++) x[i]++;

Pointer arithmetic Ü Integer math operations can be used with pointers. Ü If you

Pointer arithmetic Ü Integer math operations can be used with pointers. Ü If you increment a pointer, it will be increased by the size of whatever it points to. int *ptr = a; *(ptr+2) *ptr a[0] a[1] a[2] int a[5]; a[3] *(ptr+4) a[4]

printing an array void print_array(int a[], int len) { for (int i=0; i<len; i++)

printing an array void print_array(int a[], int len) { for (int i=0; i<len; i++) n o i s er v cout << "[" << i << "] = " rray a << a[i] << endl; } void print_array(int *a, int len) { for (int i=0; i<len; i++) cout << "[" << i << "] = " << *a++ << endl; } n sio r e v po r e t in

Passing pointers as parameters void swap( int *x, int *y) { int tmp; tmp

Passing pointers as parameters void swap( int *x, int *y) { int tmp; tmp = *x; *x = *y; *y = tmp; }

Pointer Parameters Ü Pointers are passed by value (the value of a pointer is

Pointer Parameters Ü Pointers are passed by value (the value of a pointer is the address it holds). Ü If we change what the pointer points to the caller will see the change. Ü If we change the pointer itself, the caller won't see the change (we get a copy of the pointer)

C++ strings ÜA string is a null terminated array of characters. null terminated means

C++ strings ÜA string is a null terminated array of characters. null terminated means there is a character at the end of the array that has the value 0 (null). ÜPointers are often used with strings: ull) n char *msg = “RPI”; msg 'R' 'P' 'I' 0 o zer (

String Example - Count the chars int count_string( char *s) { int n=0; inted

String Example - Count the chars int count_string( char *s) { int n=0; inted o p g n i e th while th s not null i while (*s) { to by s n++; increment count s++; to point to the next char t s se } return(n); }

Example Ü Ü Ü *a contents of a &a address of a int *a

Example Ü Ü Ü *a contents of a &a address of a int *a contents of a is of type int => a is an address of an int void my_function(int *a) { int p = 10; *a = 5; // The contents of a becomes 5 a = p; // The address a becomes 10! *a = p; // The contents of a becomes 10 a = &p; // a gets the address of p, it

C++ Pointers and References void sum(double a, double b, double *c) { double result

C++ Pointers and References void sum(double a, double b, double *c) { double result = a + b; *c = result; } void sum(double a, double b, double &c) { double result = a + b; c = result; }

Dynamic Allocation Ü Dynamic allocation is the creating of an object while the program

Dynamic Allocation Ü Dynamic allocation is the creating of an object while the program is running, using the new operator. Ü The object is stored in a large free memory area called the heap (or free-store). Ü When created in this way, the object remains on the heap until you remove it. Ü The delete operator erases the object from the heap.

Creating an Object Using the new operator, we create an int object on the

Creating an Object Using the new operator, we create an int object on the heap and assign its address to P. int * P = new int; Now we can use the pointer in the same way as previous examples. *P = 25; // assign a value cout << *P << endl;

new and delete The new operator returns the address of a new object. The

new and delete The new operator returns the address of a new object. The delete operator erases the object and makes it unavailable. Student constructor called Student * p. S = new Student; . . // use the student for a while. . . delete p. S; // gone!

Using new in Functions If you create an object inside a function, you may

Using new in Functions If you create an object inside a function, you may have to delete the object inside the same function. In this example, variable p. S goes out of scope at the end of the function block. void My. Sub() { Student * p. S = new Student; // use the Student for a while. . . delete p. S; } // delete the Student // p. S disappears

Memory Leaks A memory leak is an error condition that is created when an

Memory Leaks A memory leak is an error condition that is created when an object is left on the heap with no pointer variable containing its address. This might happen if the object's pointer goes out of scope: void My. Sub() { Student * p. S = new Student; // use the Student for a while. . . } // p. S goes out of scope (the Student's still left on the heap)

Avoid Dangling Pointers To avoid using a dangling pointer, assign NULL to a pointer

Avoid Dangling Pointers To avoid using a dangling pointer, assign NULL to a pointer immediately after it is deleted. And, of course, check for NULL before using the pointer. delete p. D; p. D = NULL; . . if( p. D != NULL ) *p. D = 4. 2; // check it first. . .

Passing Pointers to Functions Passing a pointer to a function is almost identical to

Passing Pointers to Functions Passing a pointer to a function is almost identical to passing by reference. The function has read/write access to the data referenced by the pointer. This is how swap() was written in C, before C++ introduced reference parameters: void swap( int * A, int * B ) { int temp = *A; *A = *B; *B = temp; }

Const-Qualified Pointer A const-qualified pointer guarantees that the program has read-only access to the

Const-Qualified Pointer A const-qualified pointer guarantees that the program has read-only access to the data referenced by the pointer. void My. Sub( const int * A ) { *A = 50; // error A++; // ok } The pointer itself can be modified, but this has no lasting effect--the pointer is passed by value.

Constant Pointer Declaring a constant pointer guarantees only that the pointer itself cannot be

Constant Pointer Declaring a constant pointer guarantees only that the pointer itself cannot be modified. void My. Sub( int * const A ) { *A = 50; // ok A++; // error } The data referenced by the pointer can still be modified.

Arrays and Pointers An array name is assignment-compatible with a pointer to the array's

Arrays and Pointers An array name is assignment-compatible with a pointer to the array's first element. In the following example, *p refers to scores[0]. int scores[50]; int * p = scores; *p = 99; cout << scores[0]; p++; scores++; // "99" // ok // error: scores is const

Pointers in Classes Pointers are effective when encapsulated in classes, because you can control

Pointers in Classes Pointers are effective when encapsulated in classes, because you can control the pointers' lifetimes. class Student { public: Student(); ~Student(); private: string * courses; int count; }; // more. . . // array of course names // number of courses

Pointers in Classes The constructor creates the array, and the destructor deletes it. Student:

Pointers in Classes The constructor creates the array, and the destructor deletes it. Student: : Student() { courses = new string[50]; count = 0; } Student: : ~Student() { delete [] courses; }

this Pointer Ü The this pointer holds the memory address of the current object

this Pointer Ü The this pointer holds the memory address of the current object that is using the function Ü The this pointer is automatically supplied when you call a non-static member function of a class For example, clerk. display. Values(); Is actually display. Values(&clerk); Ü The actual argument list used by the compiler for display. Values() is display. Values(Employee *this) Ü The this pointer is a constant pointer Ü Data member reference Equivalent to p. Data this->p. Data n. Length this->n. Length CStr object (*this)