Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs.

Similar presentations


Presentation on theme: "Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs."— Presentation transcript:

1 Lecture 23: Pointers

2 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs t Exercises

3 3 Pointer basics Pointers are variables that contain address values. Pointers are variables used to store address values. The basic concept of a pointer is: indirect access to data values

4 4 Pointer basics Given two integer variables alpha and beta. Variable alpha is defined, declared, initialized or assigned the value of 5. int alpha=5, beta; Problem: To copy the value of alpha(5) to beta Possible Solutions: t based on direct addressing t based on indirect addressing (pointers)

5 5 Pointer basics Direct access to data values: int alpha=5; int beta; beta = alpha;

6 6 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; ptr = α beta = *ptr;

7 7 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; // & - address of operator ptr = α //indirection or dereferencing operator beta = *ptr;

8 8 Declaration of pointers How to define (declare) pointers as variables? int *p1; p1 is a variable whose memory space will be used to store addresses of integer data.

9 9 Declaration of pointers How to define (declare) pointers as variables? char *p2; p2 is a variable whose memory space will be used to store addresses of character data.

10 10 Declaration of pointers How to define (declare) pointers as variables? double *p3; p3 is a variable whose memory space will be used to store addresses of double data.

11 11 How to use pointers? int alpha=5, *ptr; ptr = α // display alpha value/contents by direct/indirect addressing // C++ notation cout<< "\n" << alpha << " " << *ptr; // C notation printf(“\n%d %d”, alpha, *ptr);

12 12 How to use pointers? int alpha=5, *ptr=α // display address of alpha, I.e. contents of ptr // C++ notation cout << "\n " << &alpha << " " << ptr; // C notation printf(“\n%d %u %o %x %X %p”, ptr,ptr,ptr,ptr,ptr,ptr);

13 13 More on Pointers Pointers and Addresses

14 14 More on Pointers and Arrays t loop to traverse all array elements using direct access based on array subscripting expressions int a[10]; for (I=0;I<10;I++) { a[I]=I; cout << endl << a[I]; } t loop to traverse all array elements using indirect access based on pointers int a[10];int *pa;pa = &a[0]; for (I=0;I<10;I++) { *pa=I; cout << endl << *pa; pa++; }

15 15 More on Pointers and Arrays char amessage[] = “Now is the time!”; char *pmessage; pmessage = “Now is the time!”;

16 16 More on Pointers and Arrays char amessage[] = “Now is the time!”; int I=0; while(amessage[I] != ‘\0’) { cout << endl << amessage[I]; I++; }

17 17 More on Pointers and Arrays char *pmessage = “Now is the time!”; while(*pmessage != ‘\0’) { cout << *pmessage; pmessage++; } =================================================== char *pmessage = “Now is the time!”; char *q; q = pmessage + strlen(pmessage); while( pmessage < q ) { cout << *pmessage; pmessage++; }

18 18 More on Pointers Array of pointers char *pname[] = { “Illegal”, “Jan”, “Feb”,... “Nov”, “Dec” }; char aname[][15] ={ “Illegal”, “Jan”, “Feb”,... “Nov”, “Dec” };

19 19 More on Pointers Multidimensional arrays and pointers int a[10][20]; int *b[10];

20 20 Pointers and function arguments Problem: function to swap contents of two variables: void swap(int, int); swap(a, b); void swap(int p1, int p2) { int temp; temp=p1; p1=p2; p2=temp; }

21 21 Pointers and function arguments The solution: addresses specified as actual arguments void swap(int *, int *); swap(&a, &b); void swap(int *p1, int *p2) { int temp; temp=*p1; *p1=*p2; *p2=temp; }

22 22 More on Pointers Address arithmetic: char a[10]; a≡ a + 0≡&a[0] a + I≡&a[I] *(a+I)≡*&a[I]≡a[I]

23 23 More on Pointers Address arithmetic:int a[10], *p, *q; Assigning initial value to a pointer:p=q=a; Increment/decrement pointer: p++; p++; p--; Add a constant to pointer: q=q+8; Subtract constant from a pointer: q-=4; Comparison of two pointers:if(p p) Subtraction of two pointers: p=a; q=a+10; q-p is 10

24 24 More on Pointers Pointers to functions int fact(int n) { if(n==0) return 1; return n*fact(n-1); } int (*pf)(int);// pointer to function that has // one int param and returns int Direct function call Indirect function call cout << fact(5); pf = fact; cout << (*pf)(5);

25 25 More on Pointers Extract from Friedman/Koffman, chapter 13

26 Pointers & Dynamic Data Structures Chapter 13

27 27 Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes t Linked list is example of dynamic data structure Node Pointer Linked list

28 28 13.1 Pointers and the “new” Operator t Pointer Declarations –pointer variable of type “pointer to float” –can store the address of a float in p float*p; t The new operator creates a variable of type float and puts the address of the variable in pointer p p = new float; t Dynamic allocation - program execution

29 29 Pointers t Actual address has no meaning t Form:type*variable; t Example:float *p; ? P

30 30 new Operator t Actually allocates storage t Form:new type; new type [n]; t Example:new float;

31 31 Accessing Data with Pointers t * - indirection operator *p = 15.5; t Stores floating value 15.5 in memory location *p - the location pointed to by p 15.5 p

32 32 Pointer Statements float*p; p = new float; *p = 15.5; cout << “The contents of the memory cell pointed to by p is “ << *p << endl; Output The contents of memory cell pointed to by p is 15.5

33 33 Pointer Operations t Pointers can only contain addresses t So the following are errors: –p = 1000; –p = 15.5; t Assignment of pointers if q & p are the same pointer type –q = p; t Also relational operations == and !=

34 34 13.2 Manipulating the Heap t When new executes where is struct stored ? t Heap –C++ storage pool available to new operator t Effect of p = new node; t Figure 14.1 shows Heap before and after executing new operator

35 35 Effect on new on the Heap

36 36 Returning Cells to the Heap t Operation –delete p; t Returns cells back to heap for re-use t When finished with a pointer delete it t Watch dual assignments and initialization t Form:deletevariable; t Example:deletep;

37 37 Exercise 25.1-25.6 Build programs based on pointers: t Exchange values of two integer variables (function swap); t Display a character string symbol by symbol on separate lines in forward and backward order; t Define the length of a character string (own version of strlen function); t Catenate two character strings (own version of strcat function); t Define a function returning the name of a month as a character string; t Operate as demo programs for pointers to functions.

38 38 Exercise 25.1-25.6 Build programs based on pointers: t Display a character string symbol by symbol on separate lines in forward and backward order;

39 39 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { int I=0; cout << endl << str << endl; while (str[I] != ‘\0’) { cout << endl << str[I]; I++; }

40 40 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { char *p = str; cout << endl << str << endl << p << endl; while ( *p != ‘\0’) { cout << endl << *p; p++; }

41 41 Exercise 25.1-25.6 Build programs based on pointers: t Define the length of a character string (own version of strlen function);

42 42 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; int strlenm(char m[]); void main() { cout << endl << strlenm(str) << endl; } int strlenm(char m[]) { int I=0, len; while (m[I] != 0x00) I++; len = I; return len; }

43 43 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; int strlenm(char *pm); void main() { char *p = str; cout << endl << strlenm(str) << “ “ << strlenm(p) << endl; } int strlenm(char *pm) { int len = 0; while (*pm != 0x00) { Ien++; pm++; ) return len; }

44 44 Exercise 25.1-25.6 Build programs based on pointers: t Copy a character string (own version of strcpy function);

45 45 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void copym(char dst[], char src[]); void main() { char newstr[20]; copym(newstr, str); cout << endl << newstr << endl; } void copym(char dst[], char src[]) { int I=0; while(( dst[I] = src[I] ) != ‘\0’)I++; }

46 46 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void copym(char *dst, char *src); void main() { char *newstr;newstr = new char[20]; copym(newstr, str); cout << endl << newstr << endl; } void copym(char *dst, char *src) { while(( *dst = *src ) != ‘\0’) { dst++; src++; } }

47 47 Before lecture end Lecture: Pointers More to read: Friedman/Koffman, Chapter 13

48 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman

49 49 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Data Structures Arrays & structs are static (compile time) Dynamic structures expand as program executes Linked list is example of dynamic data structure Node Pointer Linked list

50 50 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.1 Pointers and the new Operator Pointer Variable Declarations –pointer variable of type “pointer to float” –can store the address of a float in p float*p; The new operator creates (allocates memory for) a variable of type float & puts the address of the variable in pointer p p = new float; Dynamic allocation occurs during program execution

51 51 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers Actual address has no meaning for us Form:type*variable; Example:float *p; ? P

52 52 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley new Operator Actually allocates storage Form:new type; new type [n]; Example:new float;

53 53 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Accessing Data with Pointers indirection operator * *p = 15.5; Stores floating value 15.5 in memory location *p - the location pointed to by p 15.5 p

54 54 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Statements float *p; p = new float; *p = 15.5; cout << “The contents of the memory cell pointed to by p is “ << *p << endl; Output The contents of memory cell pointed to by p is 15.5

55 55 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Operations Pointers can only contain memory addresses So the following are errors: p = 1000; p = 15.5; Assignment of pointers is valid if q & p are the same pointer type q = p; Also relational operations == and !=

56 56 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Structs struct electric { string current; int volts; }; electric *p, *q; p and q are pointers to a struct of type electric

57 57 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Structs p = new electric; Allocates storage for struct of type electric and places address into pointer p currentvolts p ??

58 58 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley struct Member Access through a Pointer p ->current = “AC”; p ->volts = 115; Could also be referenced as (*p).current = “AC”; (*p).volts = 115; currentvolts p AC115

59 59 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley struct Member Access through a Pointer Form:p ->m Example:p ->volts cout current volts << endl; Output AC115

60 60 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers and Structs q = new electric; Allocates storage for struct of type electric and places address into pointer q Copy contents of p struct to q struct *q = *p; currentvolts p AC115 currentvolts q AC115

61 61 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers and Structs q ->volts = 220; q = p; currentvolts AC220 q AC 115 AC220 pq->currentq->volts p->currentp->volts q

62 62 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.2 Manipulating the Heap When new executes where is struct stored ? Heap –C++ storage pool available to new operator Effect of p = new electric;

63 63 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.1 Heap before and after execution of p - new node;

64 64 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning Cells to the Heap Operation delete p; Returns cells back to heap for re-use When finished with a pointer, delete it Watch –multiple pointers pointing to same address –only pointers created with new are deleted Form:delete variable; Example:delete p;

65 65 Thank You For Your Attention


Download ppt "Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs."

Similar presentations


Ads by Google