Presentation is loading. Please wait.

Presentation is loading. Please wait.

This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.

Similar presentations


Presentation on theme: "This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson."— Presentation transcript:

1 This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson Learning, 2000. COMP103 - Pointers1 Pointers (Chapter 9) A pointer keeps the address of a memory cell that is used for storing and accessing data int a;

2 COMP103 - Pointers2 Why Pointers? 1. Curious – like to know where exactly is your variable in memory, the content of a certain memory location. 2. Not sure how much memory you need for your program int A[size];

3 COMP103 - Pointers3 Computer Memory Memory can be conceptualized as a linear set of “cells” (one byte in size) with a number, referred to as “address” associated with each cell. Memory cellsVariablesAddress a 000000 000001 000002 achar

4 COMP103 - Pointers4 Variables’ data are stored in these cells int a = 10; char mystr[5]=“hello”; Variable Data and Memory Note: Different types of data require different amounts of memory Computer Memory 0 0 0 0 1 1 0 0 h h e e l l l l o o 4 bytes 5 single bytes

5 COMP103 - Pointers5 Variables’ data are stored in these cells char mystr[]=“hello”; int a = 10; a = 20; Variable Data and Memory An assignment changes the data in the memory location Variable a is bound to this memory location! Computer Memory 0 0 0 0 2 2 0 0 h h e e l l l l o o 4 bytes 5 single bytes

6 COMP103 - Pointers6 Pointer Constants (or memory address) We can think memory addresses as Pointer Constants Pointer Constants int a = 10; 1048575 1048574 1048573 000000 000001 0 0 004000 To 004003 0 0 1 1 0 0

7 COMP103 - Pointers7 Address Operator (&) Address operator (&) provides a pointer constant of the variable: usage &variable_name Pointer Constants int a = 10; &a 004000 1048575 1048574 1048573 000000 000001 0 0 004000 To 004003 0 0 1 1 0 0

8 COMP103 - Pointers8 Figure 9-4 (p.415) Address Operator & &variable gives the address of the variable &a and &b. Result: 142300 142301 (note: this does not work in Visual C++!!) Variable name Address

9 COMP103 - Pointers9 Pointer Variable A pointer variable is a variable that stores a memory location (address) Pointers are declared using a “*” after the type int a = 10; // a pointer variable!!! int *p; p = &a; Pointer Constants a p 1048575 1048574 1048573 000000 000001 0 0 004000 To 004003 0 0 1 1 0 0 4000

10 COMP103 - Pointers10 Pointer Variable Declaration Type of data at the Memory location Figure 9-10 (p.419) Variable Name

11 COMP103 - Pointers11 Declaring Pointer Variables Figure 9-11 (p.419)

12 COMP103 - Pointers12 Don’t get confused Pointer variable, p does not hold the value of a points to the memory location of a is a variable itself has its own memory location (1002300) Pointer Constants a p 1048575 1048574 1048573 000000 000001 0 0 004000 To 004003 0 0 1 1 0 0 4000 1002300 int a; int *p; a=10; P = &a;

13 COMP103 - Pointers13 Multiple Pointers to a Variable We may have multiple pointer variables pointing to the same memory cell! What are their values? a = ? &a = ? p = ? q = ? Figure 9-7 (p.417)

14 COMP103 - Pointers14 Multiple Pointers to One Variable How? int a, *p, *q, *r; p = &a; q = &a; r = q; Figure 9-6 (p.425)

15 COMP103 - Pointers15 Multiple Pointers to a Variable int x; int *p, *q; p = &x; q = &x; Changing the variable x does not affect the pointers p and q Figure 9-8 (p.418)

16 COMP103 - Pointers16 Un-initialized Pointers Figure 9-12 (p.421)

17 COMP103 - Pointers17 Initialize Pointer Variables int *p = &x; // set a pointer to nothing int *p = NULL; Figure 9-13 (p.421)

18 COMP103 - Pointers18 Multiple Bindings The power of pointers! A pointer may be used to access different variables. p = &a p = &b p = &c Figure 9-15 (p.424)

19 COMP103 - Pointers19 Using pointers - Indirection (*) We can use the pointer variable to access the variable it “points” to by Placing a * before a pointer variable, p  refers to the content of the address of the variable given in p. int a, *p; a=5; p = &a; cout << p << *p; Result: 100203 5 This is sometimes called “ de-referencing” the pointer 5 a 100203 p Address

20 COMP103 - Pointers20 Address Operator (&) and Indirection (*) & & * * inverse operators Example: int x=5; cout << *(&x); // *(&x) is just x Indirection Address Operator &a reads “give me the memory address of the variable a” *p reads “give me the content of the memory address which is stored in the pointer variable p”

21 COMP103 - Pointers21 Indirection Operator * Using the indirection operator * Assume: p = &x; Possible ways of adding 1 to variable x: x++; x = x + 1; *p = *p + 1;

22 COMP103 - Pointers22 Add Two Numbers using Pointers How do we achieve the following effects using pointers? r = a + b Figure 9-14 (p.423)

23 COMP103 - Pointers23 More Examples Assume: int *p, *q; p = &x; q = &x; Figure 9-8 (p.418)

24 COMP103 - Pointers24 Dereferencing garbage pointers int a = 0; int *p; a = a + *p; // What will happen????

25 COMP103 - Pointers25 References vs. Pointers SUPERMAN (same person [reference]) CLARK KENT PERSON (Pointing to Superman [two different people]) *PERSON = Superman (What is he pointing to? Superman)

26 COMP103 - Pointers26 References versus Pointers Reference and pointers are different a num memory A reference shares the same memory location with other variables. int a; int &num = a; // num IS a A pointer is a variable. It points to a memory location. You have to use the (*) indirection operator to access the memory location at ‘a’; int a; int *p = &a; Cout << *p // same a ap 6 6

27 COMP103 - Pointers27 Parameter Passing - by Value Variables a and x use different memory cells. different copies Figure 9-17(a) (p.426)

28 COMP103 - Pointers28 same copy Parameter Passing - by Reference Variables a and x share the same memory cell. Figure 9-17(b) (p.426)

29 COMP103 - Pointers29 Parameter Passing - by Pointers Pointer variables, px and py refer to the memory cells of a and b. Figure 9-17(c) (p.417)

30 COMP103 - Pointers30 Pointers as Formal Parameters When we use pointer variables as formal parameters, we achieve the same effects of parameter passing by reference. by-reference: void exchange(int &x, int &y) by-pointer: void exchange(int *px, int *py)

31 COMP103 - Pointers31 Functions Returning Pointers Figure 9-18 (p.427)

32 COMP103 - Pointers32 Note in returning pointers Never return a pointer to a local variable. You’ll get a warning message Must point to a variable in the calling function void main() { int a, b, *p; … p = smaller( &a, &b ); … } int *smaller (int *px, int *py) { int temp = (*px < *py)? *px : *py; return (&temp); } This is bad! Don’t do it.

33 COMP103 - Pointers33 Pointer Indirection (Pointers to Pointers) What is a? &a? *a? p? &p? *p? **p? q? &q? *q? **q? 58 Figure 9-19 (p.428)

34 COMP103 - Pointers34 Pointers Indirection How to access a from p? *p How to access a from q? **q How to access a from r? ***r Figure 9-20 (p.429) 58

35 COMP103 - Pointers35 Casting Pointers (DO NOT DO!) What if we want to have pc pointing to a? Warning: You're advised not to cast pointers unless absolutely necessary. pc = (char *) &a; Figure 9-21 (p.433)

36 COMP103 - Pointers36 Pointer Types Must Match Figure 9-22 (p.433)

37 COMP103 - Pointers37 Lvalue vs Rvalue (Ch 9-10,p.434-436) An C++ expression is either a rvalue or lvalue. A rvalue expression appears at the right of an assignment. It refers to a value that be assigned to a memory cell, i.e. can be used to supply a value for further use, e.g. examine or copy the value. Examples: x= 5; y= a+2; z=a*6;x=a[2]+3; i=i++; A lvalue expression appears at the left of an assignment. It identifies a memory cell that is going to receive a rvalue, i.e. the memory cell is being modified. Example: a = …a[5] = …(a) = …*p = …

38 COMP103 - Pointers38 Arrays and Pointers The name of an array points only to the first element not the whole array, i.e. the variable name of an array is a pointer variable. Figure 9-25 (p.443)

39 COMP103 - Pointers39 Array Name is a pointer constant Example on p.443 of text (where is the array in memory?) #include void main() { // Demonstrate array name is a pointer constant int a[5]; cout << "Address of a[0]: " << &a[0] << endl << "Name as pointer: " << a << endl; } /* result: Address of a[0]: 0x0065FDE4 Name as pointer: 0x0065FDE4 */

40 COMP103 - Pointers40 Dereference of An Array Name Figure 9-26 (p.444) How to obtain the value of a[0] using pointer operator, “*”?

41 COMP103 - Pointers41 Array Names as Pointers To access an array, any pointer to the first element can be used instead of the name of the array. We could replace *p by *a Figure 9-27 (p.444)

42 COMP103 - Pointers42 Multiple Array Pointers Both a and p are pointers to the same array. Figure 9-28 (p.445)

43 COMP103 - Pointers43 Pointer Arithmetic Given a pointer p, p+n refers to the element that is offset from p by n positions. Figure 9-29 (p.446)

44 COMP103 - Pointers44 Pointer Arithmetic & Different Types address = pointer + (offset * size of element) Figure 9-30 (p.446)

45 COMP103 - Pointers45 *(a+n) is identical to a[n] Dereferencing Array Pointers Figure 9-31 (p.447)

46 COMP103 - Pointers46 Pointers — Arrays Duality int a[10]; You can think of ‘ a ’ as really a pointer. a[0] = *(a+0) = memory at (a+0) a[1] = *(a+1) = memory at (a+1) a[2] = *(a+2) = memory at (a+2)

47 COMP103 - Pointers47 Example: Find Smallest (Figure 9-32, p.447) Figure 9-32 (p.447)

48 COMP103 - Pointers48 Pointer to 2-Dimensional Arrays table[i][j] What is **table? Figure 9-33 (p.450)

49 COMP103 - Pointers49 Passing an Array to a Function Caller program: func( arrayName, size ); Called program: int func( int arr [ ], int size ) {…}// preferred o r int func( int *arr, int size ) {…}// same effect Arrays are passed to a function by reference.

50 COMP103 - Pointers50 Variables for Multiplying Array Elements by Two Figure 9-34 (p.452) Program 9-12 (p.452)

51 COMP103 - Pointers51 Right-Left Rule Concept int * p; reads “p is a pointer (2) to integer (4)” int table [4]; reads “table is an array of 4 (1) integers (2)” int *a[5]; reads “a is an array of 5 (1) pointers (2) to integer (4)” int ( *a )[5]; reads “a is a pointer (2) to an array of 5 (3) integers (4)” (page 454)

52 COMP103 - Pointers52 Array of Pointers & Pointer to Array

53 COMP103 - Pointers53 MEMORY MANAGEMENT DYANMIC MEMORY STATIC MEMORY Until now, we have only learned about static memory Declaration of large memory variables (arrays) must be determined before the program is compiled. We can “ask” for memory while the program is running. We can allocate and release memory ourselves! More powerful programming ability (also more potential for errors!)

54 COMP103 - Pointers54 Memory Allocation { int a[200]; int *ptr = a; … } int *ptr = new int[200]; … delete [] ptr; Figure 9-35 (p.455)

55 COMP103 - Pointers55 Conceptual View of Memory (DYNAMIC MEMORY) Figure 9-37 (p.456)

56 COMP103 - Pointers56 Dynamic Memory C++ “new” keyword new ;// allocate size of the type new [size];// allocate an array Asks the Operating System to return you a pointer to a “chunk” of data.

57 COMP103 - Pointers57 Allocating Memory Operating System Manages dynamic memory. You have: int *p; p = new int[1000]; Ask OS to find a segment Of memory of 1000*4 btyes OS returns the address. So, you need a pointer to the type you requested. If you request, you need an pointer. If you request, you need a pointer.

58 COMP103 - Pointers58 Allocating memory using “ new ” int *p; 8002 8006 8010 8014 8018 8022 8026 new returns the address to the “start” of the memory it allocated p = new int[7]; p is assigned 8002 p[0] = *(p) = *(p+0) = ? p[1] = *(p+1) = ? p[2] = *(p+2) = ? p[0] p[1] p[2]

59 COMP103 - Pointers59 Dynamic Memory Allocation Request for “unused” memory from the Operating System int *p, n=10; p = new int; p = new int[100]; p = new int[n]; p new p p

60 COMP103 - Pointers60 Dynamic Memory Allocation Example Need an array of unknown size main() { cout << “How many students? “; cin >> n; int *grades = new int; int mark; int i; for(i=0; i < n; i++) { cout << “Input Grade for Student” << (i+1) << “ ? :”; cin >> mark; grades[i] = mark; }... printMean( grades, n ); // call a function with dynamic array... }

61 COMP103 - Pointers61 Dynamic Memory C++ “delete” keyword delete address; // delete one element at address delete [] address; // delete array at address How can we specify what the address is? We have pointer. Pointer variables store addresses.

62 COMP103 - Pointers62 Freeing (or deleting) Memory Operating System Manages dynamic memory. The memory you request by “new” is not usable by Other programs until you tell the OS you don’t need it anymore. We call this “freeing” or “releasing” or “deleting” memory. How does the OS know which piece of memory you are freeing? You give it the address. Int *p; p = new int [1000]; delete [] p; // delete (or free) the array at p NOTICE, the value of p will not change! However, it is now no longer pointer to value memory. Allocated Memory Free this Memory. OS marks it as available.

63 COMP103 - Pointers63 Freeing (or deleting) Memory Figure 9-40 (p.460)

64 COMP103 - Pointers64 Freeing (or Deleting) memory “ delete ” is a keyword delete ; // a variable example: int a; int *p=&a; delete p; delete [] ; // an array example: int *p = new int[1000]; delete [] p;

65 COMP103 - Pointers65 Dynamic Memory Dynamic Memory is very powerful C++ trusts you as the programmer to manage you own memory While this gives you lots of control, it is easy to make mistakes. Dynamic memory bugs are the most common of large software written in C++.

66 COMP103 - Pointers66 The Dangling Pointer Bug Be careful when you delete memory pointed to by p, you are not erasing a location that some other pointer q is pointing to. int *p, *q; P = new int; q = p; delete p; // q is a dangling pointer p q int p q delete p

67 COMP103 - Pointers67 Memory Leak Problem (bug) Make sure to delete memory when finished int *p; p = new int[100]; int a; NO ONE HAS ACCESS TO THIS MEMORY 100 integers p = &a; a a 100 integers a a This memory is un-addressable And it is reserved until your program terminates (it has leaked from the system)

68 COMP103 - Pointers68 Dynamic Memory Allows you to create “logical” structures by piecing together pointers + dynamic memory For example, how could we build a 2D array using Dynamic Memory?

69 COMP103 - Pointers69 A Dynamic 2D Array – An array of pointers int **table; // a ragged array Figure 9-41 (p.461)

70 COMP103 - Pointers70 Allocation of 2D Array int **data; int rows=3, cols=4; data = new int*[ rows ]; Computer’s Memory data = 102000 data[i] is a int * (points to int!) // allocate row’s data for(int i=0; i < rows; i++) { data[i] = new int[cols]; } i=0 data[i] = 008004 008004 008008 008012 008016 i=0 008004 009020 009024 009028 009032 i=1 009020 i=1 data[i] = 009020 007392 007396 007400 007404 i=2 007392 i=2 data[i] = 007392 // Initialize data for(i=0; i < rows; i++) for(int j=0; j< cols; j++) { data[i][j] = 0; // or *(*(data+i)+j)=0 } 0 0 0 0 0 0 0 0 0 0 0 0 102000 102004 102008 (array of int *)

71 COMP103 - Pointers71 Deleting a 2D Array Computer’s Memory // delete row’s data for(int i=0; i < rows; i++) { delete [ ] data[i]; } 102000 102004 102008 delete memory at data[0] = 008004 delete memory at data[1] = 009020 delete memory at data[2] = 007392 008004 008008 008012 008016 i=0 008004 0 0 0 0 009020 009024 009028 009032 i=1 009020 0 0 0 0 007392 007396 007400 007404 i=2 007392 0 0 0 0 DELETED delete memory at data = 102000 delete [ ] data;

72 COMP103 - Pointers72 Using Dynamic Arrays Figure 9-43 (p.465)

73 COMP103 - Pointers73 Implementation of Dynamic Array Figure 9-44 (p.465) Complete examples Programs 9-15 to 9-23, pp. 466-470.

74 COMP103 - Pointers74 Summary Introduced Pointers and Dynamic Memory Pointers are special variables that point to memory locations New declaration int *p; char *p; int **p; char ***p; 2 new operators p = &a; // address of a *p = 5; // Indirection operator *(p)

75 COMP103 - Pointers75 Summary Pointers relationship to arrays int a[10]; int *p; p = a; // a is really a pointer too! p = &a[1]; Passing pointers to functions Pointer Arithmetic *(a+1) same as a[1] *(a+9) same as a[9]

76 COMP103 - Pointers76 Summary Dynamic Memory new and delete calls int *p = new int[100]; int *a = new int; delete a; delete [] p; Complex Uses for Dynamic Memory Example: Dynamic 2D array int **table = new int*[3]; tables[0] = new int[10]; tables[1] = new int[2]; tables[2] = new int[100];

77 COMP103 - Pointers77 Summary: Pointers and your sanity Pointers are very powerful Allow you to directly access the computer’s memory This freedom can cause problems Remember Avoid Memory Leaks, Dangling Pointers Don’t access uninitialized pointers! Be kind to others! int *bad_student = new int[1000000000000000]; 


Download ppt "This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson."

Similar presentations


Ads by Google