Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 25: Practical Training on Pointers. 2 Lecture Contents: t Reminder on Arrays t Reminder on Strings t Reminder on Pointers t Demo programs, Exercises.

Similar presentations


Presentation on theme: "Lecture 25: Practical Training on Pointers. 2 Lecture Contents: t Reminder on Arrays t Reminder on Strings t Reminder on Pointers t Demo programs, Exercises."— Presentation transcript:

1 Lecture 25: Practical Training on Pointers

2 2 Lecture Contents: t Reminder on Arrays t Reminder on Strings t Reminder on Pointers t Demo programs, Exercises t Quiz on Pointers and Strings

3 3 Reminder on Arrays t Reminder on Arrays

4 4 Array: a collection of data items of the same type How to define (declare) an array: int a[6]; float b[10][20]; char c[7][12][2];

5 5 4 Arrays t Language restrictions –Subscripts are denoted as integer valued expressions within brackets: [ ] –Base type can be any fundamental type, or library-defined type, or programmer-defined type

6 6 5 Arrays –The index type is always integer and the index range must be 0... n -1 where n is a programmer-defined constant expression. –Parameter passing style Always call by reference (no indication necessary)

7 7 16 Remember t Arrays are always passed by reference –Artifact of C  Can use const if array elements are not to be modified t You do not need to include the array size within the brackets when defining an array parameter t Initialize array with 0 or some other known value

8 8 Reminder on Strings t Reminder on Strings

9 9 Reminder on Strings t C style strings – 1D char arrays – char name[20]; – Run time library functions (#include ) t C++ style strings – STL class string (#include ) – string name; – Operator + and Methods

10 10 Reminder on Strings t C style strings – 1D array of characters ending with null terminator ‘\0’ – first char in ASCII table – char name[20]; – char city[7] = “Dallas”; // C-string – Char city2[] = {‘D’,’a’,’l’,’l’,’a’,’s’}; // array of chars – Run time library functions (#include )

11 11 Reminder on Strings t C style strings. Input Output of C strings – Suppose s is array for C string – cout << s; // to display on the console – Reading string from keyboard – char city[9]; cin >> city; // New York – Problem: input ends with whitespace character – Solution: use cin.getline() fun from – cin.getline(city, 80, ’\n’);

12 12 Reminder on Strings t C++ style strings – STL class string (#include ) – string name; – string message = “Programming”; – Operator + and Methods – length() message.length() – size() mssage.size() – at(index) message.at(0)

13 13 Reminder on Strings t C++ style strings – By default initialized as empty string or string with noo characters – Empty string literal is “” – String index.at(i) – Subsript operator: cout<< message[0]; – Comparing strings: all six rel operators

14 14 Reminder on Strings t C++ style strings – Reading strings – String city; cin >> city; // New York – Problem: input ends with whitespace character – Solution: use getline fun from header – getline(cin, city, ’\n’);

15 15 Reminder on Pointers t Reminder on Pointers

16 16 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

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

18 18 Declaration of pointers How to define (declare) pointers as variables? int *p1; char *p2; float *p3;

19 19 More on Arrays, Strings, Pointers

20 20 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++; }

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

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

23 23 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++; }

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

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

26 26 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; }

27 27 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; }

28 28 More on Pointers Address arithmetic: Given array: char a[10]; int I – array subscript with range of valid values 0…9 a ≡ a + 0≡ &a[0] a + I≡ &a[I] *(a+I)≡ *&a[I] ≡ a[I]

29 29 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);

30 30 13.9 Common Programming Errors t Use the * de-referencing operator t Operator -> member t *p refers to the entire node t p->x refers to member x t new operator to allocate storage t delete de-allocates storage t Watch out for run-time errors with loops t Don’t try to access a node returned to heap

31 31 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.

32 32 Exercise 25.1-25.6 Build programs based on pointers: t Display a C-style string symbol by symbol on separate lines in forward and backward order; – Using array subscript – Using pointer and test null terminator – Using pointer and test end array address

33 33 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++; }

34 34 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++; }

35 35 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { char *p = str; cout << endl << str << endl << p << endl; while ( p < str + strlen(str)) { cout << endl << *p; p++; }

36 36 Exercise 25.1-25.6 Build programs: t Display a C++-style string symbol by symbol on separate lines in forward and backward order; – Using methods.at(i) and.length() string b="Sofia"; cout << endl << endl; for(i=0; i<b.length(); i++) cout << b.at(i) << " ";

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

38 38 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; }

39 39 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; }

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

41 41 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++; }

42 42 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++; } }

43 43 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

44 44 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

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

46 46 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

47 47 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

48 48 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 ??

49 49 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

50 50 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

51 51 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

52 52 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

53 53 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;

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

55 55 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;

56 56 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.4 The Stack Abstract Data Type A stack is a data structure in which only the top element can be accessed LIFO (Last-In First-Out) Operations –push –pop

57 57 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Stack of Characters *C+2*C+2 s

58 58 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The C++ stack Class Must include stack library #include Declare the stack stack stack-name; E.g. stack nameStack; stack s;

59 59 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some stack Member Functions void push(const T&) T top( ) const void pop( ) bool empty( ) const

60 60 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example x = s.top( ); // stores ‘*’ into x, stack unchanged s.pop( ); // removes top of stack s.push(‘/’); // adds ‘/’ to top of stack *C+2*C+2 s C+2C+2 s /C+2/C+2 s

61 61 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.5 The Queue ADT List-like structure where items are inserted at one end and removed from the other First-In-First-Out (FIFO) E.g. a customer waiting line

62 62 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.12 Queue of customers

63 63 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The C++ queue Class Must include queue library #include Declare the stack queue queue-name; E.g. queue customers;

64 64 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member Functions of queue Class void push(const T&) T top( ) const void pop( ) bool empty( ) const int size( ) const

65 65 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.6 Binary Trees Like a list with additional pointer Nodes contain 2 pointers –right pointer –left pointer –0 (leaf nodes), 1, or 2 successor nodes Binary Tree –empty –root left and right sub-trees

66 66 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.13 Binary trees

67 67 Thank You For Your Attention


Download ppt "Lecture 25: Practical Training on Pointers. 2 Lecture Contents: t Reminder on Arrays t Reminder on Strings t Reminder on Pointers t Demo programs, Exercises."

Similar presentations


Ads by Google