lecture 25: practical training on pointers. 2 lecture contents: t reminder on arrays t reminder on...
TRANSCRIPT
Lecture 25:Practical Training on Pointers
2
Lecture Contents:
Reminder on Arrays Reminder on Strings Reminder on Pointers Demo programs, Exercises Quiz on Pointers and Strings
3
Reminder on Arrays
Reminder on Arrays
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];
54
Arrays 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
65
Arrays– The index type is always integer and the
index range must be0 ... n-1• where n is a programmer-defined constant
expression.
– Parameter passing style• Always call by reference (no indication
necessary)
716
Remember Arrays are always passed by reference
– Artifact of C Can use const if array elements are not to be
modified You do not need to include the array size within
the brackets when defining an array parameter Initialize array with 0 or some other known value
8
Reminder on Strings
Reminder on Strings
9
Reminder on Strings
C style strings– 1D char arrays– char name[20];– Run time library functions (#include <cstring>)
C++ style strings– STL class string (#include <string>)– string name;– Operator + and Methods
10
Reminder on Strings
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
<cstring>)
11
Reminder on Strings
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
<iostream>– cin.getline(city, 80, ’\n’);
12
Reminder on Strings
C++ style strings– STL class string (#include <string>)– string name;– string message = “Programming”;– Operator + and Methods– length() message.length()– size() mssage.size()– at(index) message.at(0)
13
Reminder on Strings
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
Reminder on Strings
C++ style strings– Reading strings– String city; cin >> city; // New York– Problem: input ends with whitespace
character– Solution: use getline fun from header
<string>– getline(cin, city, ’\n’);
15
Reminder on Pointers
Reminder on Pointers
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
Pointer basics
Indirect access to data values:int alpha=5, beta, *ptr;
// & - address of operatorptr = α
//indirection or dereferencing operator
beta = *ptr;
18
Declaration of pointers
How to define (declare) pointers as variables?
int *p1; char *p2; float *p3;
19
More onArrays, Strings,
Pointers
20
More on Pointers and Arrays
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]; }
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
More on Pointers and Arrays
char amessage[] = “Now is the time!”;
char *pmessage;
pmessage = “Now is the time!”;
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
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
More on Pointers
// Array of pointers
char *pname[] = { “Illegal”, “Jan”, “Feb”,
. . . “Nov”, “Dec” };
// 2D array
char aname[][15] ={ “Illegal”, “Jan”, “Feb”,
. . . “Nov”, “Dec” };
25
More on Pointers
Multidimensional arrays and pointers
int a[10][20];
int *b[10];
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
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
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
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 callcout << fact(5); pf = fact;
cout << (*pf)(5);
30
13.9 Common Programming Errors
Use the * de-referencing operator Operator -> member *p refers to the entire node p->x refers to member x new operator to allocate storage delete de-allocates storage Watch out for run-time errors with loops Don’t try to access a node returned to heap
31
Exercise 25.1-25.6
Build programs based on pointers: Exchange values of two integer variables (function swap); Display a character string symbol by symbol on separate
lines in forward and backward order; Define the length of a character string (own version of
strlen function); Catenate two character strings (own version of strcat
function); Define a function returning the name of a month as a
character string; Operate as demo programs for pointers to functions.
32
Exercise 25.1-25.6
Build programs based on pointers:
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
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
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
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
Exercise 25.1-25.6
Build programs: 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
Exercise 25.1-25.6
Build programs based on pointers:
Define the length of a character string (own version of strlen function);
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
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
Exercise 25.1-25.6
Build programs based on pointers:
Copy a character string (own version of strcpy function);
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
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++; }
}
43Copyright © 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
44Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Pointers
• Actual address has no meaning for us
• Form: type *variable;
• Example: float *p;
?
P
45Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
new Operator
• Actually allocates storage
• Form: new type;
new type [n];
• Example: new float;
46Copyright © 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
47Copyright © 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
48Copyright © 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
current voltsp? ?
49Copyright © 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;
current voltspAC 115
50Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
struct Member Access through a Pointer
• Form: p ->m
• Example: p ->voltscout << p->current << p->volts << endl;
• OutputAC115
51Copyright © 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;current voltsp
AC 115
current voltsqAC 115
52Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Pointers and Structs
q ->volts = 220;
q = p;
current voltsAC 220
q
AC 115
AC 220
p q->current q->voltsp->current p->volts
q
53Copyright © 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;
54Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Figure 13.1 Heap before and after execution of p - new node;
55Copyright © 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;
56Copyright © 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
57Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
A Stack of Characters
*
C
+
2
s
58Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The C++ stack Class
• Must include stack library#include <stack>
• Declare the stackstack <type> stack-name;
• E.g.stack <string> nameStack;stack <char> s;
59Copyright © 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
60Copyright © 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
s
C
+
2
s
/
C
+
2
s
61Copyright © 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
62Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Figure 13.12 Queue of customers
63Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The C++ queue Class
• Must include queue library#include <queue>
• Declare the stackqueue <type> queue-name;
• E.g. queue <string> customers;
64Copyright © 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
65Copyright © 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
66Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Figure 13.13 Binary trees
67
Thank You
For
Your Attention