oop Lecture 17


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • The dynamic memory allocation allows program to adjust its use of memory depending on the input.
  • Much like a java reference (but more explicit) A pointer is a variable that contains the address of an object in memory. Line 1 – x is an integer, give it value 10 Line 3 – p gets the address of x
  • Just like java. But you have to think about pointers.
  • No garbage collection.
  • oop Lecture 17

    1. 1. Object Oriented Programming using C++ Pointers overview Lecture 17
    2. 2. What is a Pointer?• A P o i n t e r provides a way of accessing a variable without referring to the variable directly.• The m e c h a n i s m used for this purpose is the address of the variable.• A variable that stores the address of another variable is called a p o in t e r v a r ia b l e .
    3. 3. Pointer Variables• Pointer variable (pointer): variable that holds an address• Can perform some tasks more easily with an address than by accessing memory via a symbolic name: – Accessing unnamed memory locations – Array manipulation – etc.
    4. 4. Why Use Pointers?• To operate on data stored in an array• To enable convenient access within a function to large blocks data, such as arrays, that are defined outside the function.• To allocate space for new variables d y n a mic a l l y – that is during program execution
    5. 5. Using Pointers• To use a pointer we need to – Store the address of another variable of the appropriate type in it.• How w e o b t a in t h e a d d r e s s o f a v a r ia b le
    6. 6. Pointer Data Types and Pointer Variables• Pointer variable: variable whose content is a memory address• Syntax to declare pointer variable: dataType *identifier;• Address of operator: Ampersand, &• Dereferencing operator/Indirection operator: Asterisk, *
    7. 7. T h e Address-Of O p e r a t o r (&)• The address-of operator, & , is a unary operator that obtains the address in memory where a variable is stored. i n t n u m b e r = 12 3 4 ; i n t * p n u m b e r = & n u m b e r ; / stores address of / / number in pnumber / c ha r a = ‘ a ’ ; c h a r *p a = & a ; / stores address of a in pa. /
    8. 8. The Indirection Operator• H o w p o in t e r v a r ia b le is u s e d t o a c c e s s the c o nte nts o f me mo ry lo c a t io n ?• The i n d i r e c t i o n o p e r a t o r , * is used for this purpose. ---- c o u t << * p n u m b e r ;
    9. 9. The Indirection Operatorint x= 4;int *px = &x; //stores address of variable x in variable px Add re Add re s ses cout<<“The number is:”<<x; s ses x 4 13 1 The output is:x 4 13 1 0 0 13 1 13 1 2 p 13 10 2 13 1 The number is: 4 13 1 x 4 4 13 1 13 1 6 6 cout<<“The number accessed by pointer variable is: ”<<*px T he output is: The number is: 4
    10. 10. The Indirection Operator int x= 4; int *px = &x; //stores address of variable x in variable px Ad dre s s es x 43 13 1 0 13 1 2 p 13 10 13 1 x 4 13 1 6*px = 3 / T his statement means assign 3 to a variable “p o in t e d t o ” by p x . /The data is accessed indirectly
    11. 11. pointerint x = 10;int *p; pp = &x; 10 xp gets the address of x in memory.
    12. 12. What is a pointer?int x = 10;int *p; pp = &x; 20 x*p = 20;*p is the value at the address p.
    13. 13. What is a pointer? Declares a pointerint x = 10; to an integerint *p;p = &x; & is address operator gets address of x*p = 20; * dereference operator gets value at p
    14. 14. Pointers• Statements: int *p; int num;
    15. 15. Pointers
    16. 16. Pointers
    17. 17. Pointers
    18. 18. Pointers• Summary of preceding diagrams – &p, p, and *p all have different meanings – &p means the address of p – p means the content of p – *p means the content pointed to by p, that is pointed to by the content of memory location
    19. 19. Pointers
    20. 20. Getting the Address of a Variable• Each variable in program is stored at a unique address• Use address operator & to get address of a variable: int num = -23; cout << &num; // prints address // in hexadecimal
    21. 21. Pointer Variables• Definition: int *intptr;• Read as: “intptr can hold the address of an int”• Spacing in definition does not matter: int *intptr; // same as above int* intptr; // same as above
    22. 22. Pointer Variables• Assignment: int *intptr; intptr = &num;• Memory layout: num intptr 25 0x4a00• Can access num using intptr and indirection operator *: address of num: 0x4a00 cout << *intptr << endl;
    23. 23. Assigning a value to a dereferenced pointerA pointer must have a value before you can dereference it (follow the pointer). int *x; int foo; *x=3; int *x; x = &foo; ing!!! R!!! o anyth *x=3;ERRO n’t point t sx doe e is fin foo this o x po ints t
    24. 24. Pointers to anything x some intint *x;int **y; y some *int some intdouble *z; z some double
    25. 25. The Relationship Between Arrays and Pointers• Array name is starting address of array int vals[] = {4, 7, 11}; starting address of vals: 0x4a00 4 7 11 cout << vals; // displays 0x4a00 cout << vals[0]; // displays 4
    26. 26. Pointers and Arrays• An array name is basically a const pointer.• You can use the [] operator with a pointer: int *x; int a[10]; x = &a[2]; x is “the address of a[2] ”
    27. 27. Pointer Arithmetic • Operations on pointer variables:Operation Example int vals[]={4,7,11}; int *valptr = vals;++, -- valptr++; // points at 7 valptr--; // now points at 4+, - (pointer and int) cout << *(valptr + 2); // 11+=, -= (pointer valptr = vals; // points at 4and int) valptr += 2; // points at 11- (pointer from pointer) cout << valptr–val; // difference //(number of ints) between valptr // and val
    28. 28. 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+4) *ptr a[0] a[1] a[2] a[3] a[4] int a[5];
    29. 29. Initializing Pointers• Can initialize at definition time: int num, *numptr = &num; int val[3], *valptr = val;• Cannot mix data types: float cost; int *ptr = &cost; // won’t work
    30. 30. Comparing Pointers• Relational operators (<, >=, etc.) can be used to compare addresses in pointers• Comparing addresses in pointers is not the same as comparing contents pointed at by pointers: if (ptr1 == ptr2) // compares // addresses if (*ptr1 == *ptr2) // compares // contents
    31. 31. Allocating memory using n e wPoint *p = new Point(5, 5);• new can be thought of a function with slightly strange syntax• new allocates space to hold the object.• new calls the object’s constructor.• new returns a pointer to that object.
    32. 32. Deallocating memory using d e l e t e// allocate memoryPoint *p = new Point(5, 5);...// free the memorydelete p;For every call to new, there must beexactly one call to delete.
    33. 33. Dynamic Memory Allocation• DMA provides a mechanism to allocate memory at run-time by the programmer• Memory Free Store – During execution of program, there is unused memory in the computer. It is called free store.• Dynamic Storage duration – Life-span of dynamic variables is defined by the programmer• The Operators new and delete are used for DMA
    34. 34. Rules to Observe• Do not use delete to free the memory not allocated by new• Do not use delete to free the same block of memory twice in succession• Use delete [ ] if you used new to allocate memory for an array
    35. 35. Void Pointer• A void* is a generic pointer. Pointer of any type can be assigned to the void pointer• Once assigned the type of void* is the same as that of assigned pointer type• Dereferencing a void* is a syntax error void* sPtr; int num; int z[3]={1,2,3}; sPtr= z; num= *sPtr; // ERROR num= *(int*) sPtr; // correct version
    36. 36. Functions• Pass by value – A copy of argument it created – The value of the passed argument is not modified – The operation is performed on the copy of passed value as argument• Pass by reference – The address of argument is passed – The value of the passed argument gets modified – This may occur by Reference variable or through pointer variables
    37. 37. 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 wont see the change (we get a copy of the pointer)
    38. 38. Pointers as Function Parameters• A pointer can be parameter• Works like reference variable to allow change to argument from within function• Requires: – asterisk * on parameter in prototype and heading void getNum(int*); // function prototype void getNum(int *ptr) // function header // ptr is pointer to an int – asterisk * in body to dereference the pointer cin >> *ptr; – address as argument to the function getNum(&num); // pass address of num to getNum
    39. 39. Pointers as Function Parametersvoid swap(int *x, int *y){ int temp; temp = *x; *x = *y; *y = temp;}int num1 = 2, num2 = -3;swap(&num1, &num2);
    40. 40. Passing pointers as arguments When a pointer is passed as an argument, it divulges an address to the called function, so the function can change the value stored at that address: void passPointer(int* iPtr){ *iPtr += 2; // note *iPtr on left! } ... int i = 3; int* iPtr = &i; passPointer(iPtr); cout << "i = " << i << endl; // prints i = 5 passPointer(&i); // equivalent to above cout << "i = " << i << endl; // prints i = 7 End result same as pass-by-reference, syntax different. (Usually pass by reference is the preferred technique.)Glen CowanRHUL Physics Computing and Statistical Data Analysis
    41. 41. Pointers vs. reference variables A reference variable behaves like an alias for a regular variable. To declare, place & after the type: void passReference(int& i){ i += 2; } ... int i = 3; int& j = i; // j is a reference variable j = 7; cout << "i = " << i << endl; // prints i = 7 passReference(j); cout << "i = " << i << endl; // prints i = 9 Passing a reference variable to a function is the same as passing a normal variable by reference.Glen CowanRHUL Physics Computing and Statistical Data Analysis
    42. 42. What to do with pointers You can do lots of things with pointers in C++, many of which result in confusing code and hard-to-find bugs. One of the main differences between Java and C++: Java doesn’t have pointer variables (generally seen as a Good Thing). To learn about “pointer arithmetic” and other dangerous activities, consult most C++ books; we will not go into it here. The main usefulness of pointers for us is that they will allow us to allocate memory (create variables) dynamically, i.e., at run time, rather than at compile time.Glen CowanRHUL Physics Computing and Statistical Data Analysis