Lecture 25:
Practical Training on Pointers
Lecture Contents:
Reminder on Arrays
Reminder on Strings
Reminder on Pointers
Demo programs, Exercises
Quiz on Pointers and Strings
2
Reminder on Arrays
Reminder on Arrays
3
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];
4
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
4
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)
5
6
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
16
7
Reminder on Strings
Reminder on Strings
8
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
9
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>)
10
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’);
11
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)
12
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
13
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’);
14
Reminder on Pointers
Reminder on Pointers
15
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
16
Pointer basics
Indirect access to data values:
int alpha=5, beta, *ptr;
// & - address of operator
ptr = α
//indirection or dereferencing operator
beta = *ptr;
17
Declaration of pointers
How to define (declare) pointers as variables?
int *p1;
char *p2;
float *p3;
18
More on
Arrays, Strings,
Pointers
19
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++; }
20
More on Pointers and Arrays
char amessage[] = “Now is the time!”;
char *pmessage;
pmessage = “Now is the time!”;
21
More on Pointers and Arrays
char amessage[] = “Now is the time!”;
int I=0;
while(amessage[I] != ‘\0’)
{
cout << endl << amessage[I];
I++;
}
22
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++;
}
23
More on Pointers
// Array of pointers
char *pname[] = { “Illegal”, “Jan”, “Feb”,
. . . “Nov”, “Dec” };
// 2D array
char aname[][15] ={ “Illegal”, “Jan”, “Feb”,
. . . “Nov”, “Dec” };
24
More on Pointers
Multidimensional arrays and pointers
int a[10][20];
int *b[10];
25
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;
}
26
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;
27
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]
28
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
cout << fact(5);
Indirect function call
pf = fact;
cout << (*pf)(5);
29
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
30
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.
31
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
32
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++;
}
}
33
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++;
}
}
34
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++;
}
}
35
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) << " ";
36
Exercise 25.1-25.6
Build programs based on pointers:
Define the length of a character string (own version of
strlen function);
37
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;
}
38
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;
}
39
Exercise 25.1-25.6
Build programs based on pointers:
Copy a character string (own version of strcpy function);
40
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++;
41
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++; }
}
42
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
43
Pointers
• Actual address has no meaning for us
P
?
• Form:
• Example:
type *variable;
float *p;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
44
new Operator
• Actually allocates storage
• Form:
new type;
new type [n];
• Example:
new float;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
45
Accessing Data with Pointers
• indirection operator *
*p = 15.5;
• Stores floating value 15.5 in memory
location *p - the location pointed to by p
p
15.5
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
46
Pointers to Structs
struct electric
{
string current;
int volts;
};
electric *p, *q;
• p and q are pointers to a struct of type
electric
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
47
Pointers to Structs
p = new electric;
• Allocates storage for struct of type electric
and places address into pointer p
p
current
?
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
volts
?
48
struct Member Access through a
Pointer
p ->current = “AC”;
p ->volts = 115;
p
current
AC
volts
115
• Could also be referenced as
(*p).current = “AC”;
(*p).volts = 115;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
49
struct Member Access through a
Pointer
• Form:
• Example:
p ->m
p ->volts
cout << p->current << p->volts << endl;
• Output
AC115
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
50
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;
p
current
AC
volts
115
q
current
AC
volts
115
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
51
Pointers and Structs
q ->volts = 220;
q
current
AC
volts
220
p->current
q->current
AC
p->volts
q->volts
115
AC
220
q = p;
p
q
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
52
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;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
53
Figure 13.1
Heap before and after execution of
p - new node;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
54
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:
• Example:
delete variable;
delete p;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
55
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
56
A Stack of Characters
*
C
+
2
s
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
57
The C++ stack Class
• Must include stack library
#include <stack>
• Declare the stack
stack <type> stack-name;
• E.g.
stack <string> nameStack;
stack <char> s;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
58
Some stack Member Functions
void push(const T&)
T top( ) const
void pop( )
bool empty( ) const
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
59
Example
x = s.top( );
s.pop( );
s.push(‘/’);
// stores ‘*’ into x, stack unchanged
// removes top of stack
// adds ‘/’ to top of stack
*
/
C
C
C
+
+
+
2
2
2
s
s
s
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
60
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
61
Figure 13.12
Queue of customers
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
62
The C++ queue Class
• Must include queue library
#include <queue>
• Declare the stack
queue <type> queue-name;
• E.g.
queue <string> customers;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
63
Member Functions of queue
Class
void push(const T&)
T top( ) const
void pop( )
bool empty( ) const
int size( ) const
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
64
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
65
Figure 13.13
Binary trees
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
66
Thank You
For
Your Attention
67
© Copyright 2026 Paperzz