SlideShare a Scribd company logo
CSC113:
COMPUTER PROGRAMMING
(THEORY = 03, LAB = 01)
Momina Moetesum
Computer Science Department
Bahria University, Islamabad
POINTERS II
Week # 13
3
REFERENCE VARIABLES EXAMPLE
#include <iostream.h>
// Function prototypes
(required in C++)
void p_swap(int *, int *);
void r_swap(int&, int&);
int main (void){
int v = 5, x = 10;
cout << v << x << endl;
p_swap(&v,&x);
cout << v << x << endl;
r_swap(v,x);
cout << v << x << endl;
return 0;
}
void r_swap(int &a, int &b)
{
int temp;
temp = a; (2)
a = b; (3)
b = temp;
}
void p_swap(int *a, int *b)
{
int temp;
temp = *a; (2)
*a = *b; (3)
*b = temp;
}
4
POINTER EXPRESSIONS AND POINTER
ARITHMETIC
 Pointer arithmetic
 Increment/decrement pointer (++ or --)
 Add/subtract an integer to/from a pointer( + or += , - or -=)
 Pointers may be subtracted from each other
 Pointer arithmetic is meaningless unless performed on an
array
 5 element int array on a machine using 4 byte ints
 vPtr points to first element v[ 0 ], which is at location
3000
 vPtr = 3000
 vPtr += 2; sets vPtr to 3008
 vPtr points to v[ 2 ]
pointer variable vPtr
v[0] v[1] v[2] v[4]
v[3]
3000 3004 3008 3012 3016
location
5
POINTER EXPRESSIONS AND
POINTER ARITHMETIC
 Subtracting pointers
 Returns the number of elements between two
addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr == 2
 Pointer comparison
 Test which pointer points to the higher numbered
array element
 Test if a pointer points to 0 (NULL)
if ( vPtr == ‘0’ )
statement
6
VOID POINTER
 Pointers assignment
 If not the same type, a cast operator must be used
 Exception: pointer to void (type void *)
 Generic pointer, represents any type
 No casting needed to convert a pointer to void pointer
 void pointers cannot be dereferenced
7
THE RELATIONSHIP BETWEEN
POINTERS AND ARRAYS
 Arrays and pointers closely related
 Array name like constant pointer
 Pointers can do array subscripting operations
 Having declared an array b[ 5 ] and a pointer bPtr
 bPtr is equal to b
bptr == b
 bptr is equal to the address of the first element of b
bptr == &b[ 0 ]
8
THE RELATIONSHIP BETWEEN
POINTERS AND ARRAYS
 Accessing array elements with pointers
 Element b[ n ] can be accessed by *(bPtr + n)
 Called pointer/offset notation
 Array itself can use pointer arithmetic.
 b[ 3 ] same as *(b + 3)
 Pointers can be subscripted (pointer/subscript
notation)
 bPtr[ 3 ] same as b[ 3 ]
EXAMPLE
//using subscript and pointer notations with
arrays
#include<iostream>
using namespace std;
int main()
{
int b[]={10,20,30,40};
int *bPtr=b;
cout<<“Array printed with:”<<endl;
cout<<“ Array subscript notation” <<endl;
for (int i=0; i<=3; i++)
cout<<“b[”<<i<<“]=”<<b[i]<<endl;
cout<<endl<<“Array/offset notation”<<endl;
for(int offset=0;offset<=3;offset++)
cout<<“*(b+”<<offset<<“)=”
<<*(b+offset)<<endl;
cout<<“ Pointer subscript notation”
<<endl;
for (int i=0; i<=3; i++)
cout<<“bPtr[”<<i<<“]=”<<bPtr[i]<<
endl;
cout<<“Pointer/offset notation <<endl;
for(int offset=0;offset<=3;offset++)
cout<<“*(bPtr+”<<offset<<“)=”<<
*(bPtr+offset)<<endl;
return 0;
}
OUTPUT
Array printed with
Array subscript notation
b[0]=10
b[1]=20
b[2]=30
b[3]=40
Pointer offset notation where the pointer is the array name
*(b+0)=10
*(b+1)=20
*(b+2)=30
*(b+3)=40
Pointer subscript notation
bPtr[0]=10
bPtr[1]=20
bPtr[2]=30
bPtr[3]=40
Pointer/offset notation
*(bPtr+0)=10
*(bPtr+1)=20
*(bPtr+2)=30
*(bPtr+3)=40
EXAMPLE
//Copying a string using array notation
and pointer notation
#include<iostream>
using namespace std;
void copy1(char *, const char *);
void copy2(char *, const char *);
int main()
{
char string1[10], *string2=“Hello”;
char string3[10],string4[]=“Good
bye”;
copy1(string1, string2);
cout<<“string1=”<<string1<<endl;
copy1(string3, string4);
cout<<“string3=”<<string3<<endl;
return 0;
}
//copy s2 and s1 using array notation
void copy1(char *s1, const char *s2)
{
for(int i=0; (s1[i]=s2[i])!=‘0’;i++)
; //do nothing
}
//copy s2 and s1 using pointer
notation
void copy1(char *s1, const char *s2)
{
for( ; (*s1=*s2)!=‘0’; s1++,s2++)
; //do nothing
}
OUTPUT
string1 =Hello
string3=Good Bye
13
ARRAYS OF POINTERS
 Arrays can contain pointers
 Commonly used to store an array of strings
char *suit[ 4 ] = {"Hearts", "Diamonds",
"Clubs", "Spades" };
 Each element of suit is a pointer to a char * (a string)
 The strings are not in the array, only pointers to the
strings are in the array
 suit array has a fixed size, but strings can be of any
size
suit[3]
suit[2]
suit[1]
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’
’
0’
’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’
’
0’
’C’ ’l’ ’u’ ’b’ ’s’
’
0’
’S’ ’p’ ’a’ ’d’ ’e’ ’s’
’
0’
14
CASE STUDY: A CARD SHUFFLING
AND DEALING SIMULATION
 Card shuffling program
 Use an array of pointers to strings, to store suit names
 Use a double scripted array (suit by value)
 Place 1-52 into the array to specify the order in which the cards are dealt
deck[2][12] represents the King of Clubs
Hearts
Diamonds
Clubs
Spades
0
1
2
3
Ace Two Three FourFive SixSeven
Eight
NineTen JackQueen
King
0 1 2 3 4 5 6 7 8 9 10 11 12
Clubs King
15
FUNCTION POINTERS
 Pointers to functions
 Contain the address of the function
 Similar to how an array name is the address of its first
element
 Function name is starting address of code that defines
function
 Function pointers can be
 Passed to functions
 Stored in arrays
 Assigned to other function pointers
16
FUNCTION POINTERS
 Example: bubblesort
 Function bubble takes a function pointer
 The function determines whether the the array is sorted
into ascending or descending sorting
 The argument in bubble for the function pointer
bool ( *compare )( int, int )
tells bubble to expect a pointer to a function that
takes two ints and returns a bool
 If the parentheses were left out
bool *compare( int, int )
would declare a function that receives two integers
and returns a pointer to a bool
 2000 Deitel & Associates, Inc.
 2000 Deitel & Associates, Inc.
Outline
1 // Fig. 5.26: fig05_26.cpp
2 // Multipurpose sorting program using function pointers
3 #include <iostream>
4
8
9 #include <iomanip>
10
12
13void bubble( int [], const int, bool (*)( int, int ) );
14bool ascending( int, int );
15bool descending( int, int );
16
17int main()
18{
19 const int arraySize = 10;
20 int order,
21
22 a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
23
24 cout << "Enter 1 to sort in ascending order,n"
25 << "Enter 2 to sort in descending order: ";
26 cin >> order;
27 cout << "nData items in original ordern";
28
29 for ( counter = 0; counter < arraySize; counter++ )
30 cout << setw( 4 ) << a[ counter ];
31
32 if ( order == 1 ) {
33 bubble( a, arraySize, ascending );
34 cout << "nData items in ascending ordern";
counter,
 2000 Deitel & Associates, Inc.
 2000 Deitel & Associates, Inc.
Outline
35 }
36 else {
37 bubble( a, arraySize, descending );
38 cout << "nData items in descending ordern";
39 }
41 for ( counter = 0; counter < arraySize; counter++ )
42 cout << setw( 4 ) << a[ counter ];
44 cout << endl;
45 return 0;
46}
47
48void bubble( int work[], const int size,
49 bool (*compare)( int, int ) )
50{
51 void swap( int * const, int * const ); // prototype
52
53 for ( int pass = 1; pass < size; pass++ )
55 for ( int count = 0; count < size - 1; count++ )
57 if ( (*compare)( work[ count ], work[ count + 1 ] ) )
58 swap( &work[ count ], &work[ count + 1 ] );
59}
60
61void swap( int * const element1Ptr, int * const element2Ptr )
62{
63 int temp;
64
65 temp = *element1Ptr;
66 *element1Ptr = *element2Ptr;
67 *element2Ptr = temp;
 2000 Deitel & Associates, Inc.
 2000 Deitel & Associates, Inc.
Outline
Program output
69
70bool ascending( int a, int b )
71{
72 return b < a; // swap if b is less than a
73}
74
75bool descending( int a, int b )
76{
77 return b > a; // swap if b is greater
than a
78}
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 1
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 2
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in descending order
89 68 45 37 12 10 8 6 4 2
20
DYNAMIC MEMORY ALLOCATION
 Dynamic Memory Allocation
 The new operator
 The delete operator
 Dynamic Memory Allocation for Arrays
21
DYNAMIC MEMORY ALLOCATION
 Static memory - where
global and static variables live
 Heap memory -
dynamically allocated at
execution time
- "managed" memory
accessed using pointers
 Stack memory - used by
automatic variables
In C and C++, three types of memory are used by programs:
22
3 KINDS OF PROGRAM DATA
 STATIC DATA: Allocated at compiler time
 DYNAMIC DATA: explicitly allocated and
deallocated during program execution by C++
instructions written by programmer using
operators new and delete
 AUTOMATIC DATA: automatically created at
function entry, resides in activation frame of
the function, and is destroyed when returning
from function
23
DYNAMIC MEMORY
ALLOCATION
 In C, functions such as malloc() are used to
dynamically allocate memory from the Heap.
 In C++, this is accomplished using the new
and delete operators
 new is used to allocate memory during
execution time
 returns a pointer to the address where the object is to be
stored
 always returns a pointer to the type that follows the new
OPERATOR NEW SYNTAX
new DataType
new DataType [IntExpression]
 If memory is available, in an area called the heap (or
free store) new allocates the requested object or array,
and returns a pointer to (address of ) the memory
allocated.
 Otherwise, program terminates with error message.
 The dynamically allocated object exists until the delete
operator destroys it.
24
25
OPERATOR NEW
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
NOTE: Dynamic data has no variable name
2000
???
ptr
5000
5000
‘B’
OPERATOR DELETE SYNTAX
delete Pointer
delete [ ] Pointer
 The object or array currently pointed to by Pointer
is deallocated, and the value of Pointer is
undefined. The memory is returned to the free
store.
 Good idea to set the pointer to the released
memory to NULL
 Square brackets are used with delete to deallocate
a dynamically allocated array. 26
27
OPERATOR DELETE
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
delete ptr;
5000
5000
‘B’
2000
ptr
???
NOTE:
delete deallocates the
memory pointed to by ptr
EXAMPLE
#include <iostream>
using namespace std;
int main()
{
int n, *p, c;
cout << "Enter an integern";
cin >> n;
p = new int[n];
cout << "Enter " << n << " integersn";
for ( c = 0 ; c < n ; c++ )
cin >> p[c];
cout << "Elements entered by you aren";
for ( c = 0 ; c < n ; c++ )
cout << p[c] << endl;
delete[] p;
return 0;
}

More Related Content

PPT
pointers
PPTX
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
PPTX
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
PDF
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
DOCX
Arrry structure Stacks in data structure
PPT
Arrays in c programing. practicals and .ppt
PPT
Unit 6 pointers
pointers
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
Arrry structure Stacks in data structure
Arrays in c programing. practicals and .ppt
Unit 6 pointers

Similar to week14Pointers_II. pointers pemrograman dasar C++.pptx (20)

PPTX
Engineering Computers L32-L33-Pointers.pptx
PPTX
Pointers in C++ object oriented programming
PDF
C++_notes.pdf
PPTX
Introduction to pointers in c plus plus .
PPTX
pointers in c programming - example programs
PDF
c programming
PPTX
C++ lectures all chapters in one slide.pptx
PPTX
C++ FUNCTIONS-1.pptx
PDF
C Programming - Refresher - Part III
PPTX
Lecture 9_Classes.pptx
PPTX
Chp4(ref dynamic)
PPT
Data structure and problem solving ch05.ppt
PPT
ch08.ppt
PPT
Pointers+(2)
PDF
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
PDF
Introduction to cpp (c++)
PPT
C++ Language
PDF
C++ normal assignments by maharshi_jd.pdf
PPT
Lecture2.ppt
PPTX
Managing console
Engineering Computers L32-L33-Pointers.pptx
Pointers in C++ object oriented programming
C++_notes.pdf
Introduction to pointers in c plus plus .
pointers in c programming - example programs
c programming
C++ lectures all chapters in one slide.pptx
C++ FUNCTIONS-1.pptx
C Programming - Refresher - Part III
Lecture 9_Classes.pptx
Chp4(ref dynamic)
Data structure and problem solving ch05.ppt
ch08.ppt
Pointers+(2)
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Introduction to cpp (c++)
C++ Language
C++ normal assignments by maharshi_jd.pdf
Lecture2.ppt
Managing console
Ad

More from hudriyah1 (19)

PPTX
522554777-Materi-4-karakter-Animasi-2d.pptx
PPTX
project penguatan profil pelajar pancasila Suara Demokrasi.pptx
PPTX
Sales Review NurHadi - April 2024.pptx
PPTX
LAPORAN PRAKTEK-WPS Office mapel pilihan.pptx
PPTX
mind mapping DKV mind mapping DKV mind mapping DKV
PDF
Desain Grafis Percetakan-Mengenal Fotografi
PPTX
PBJ SMK 5 tgl 26-08-2024 .pptx
PPTX
dmi kd 3.5 kelas XI Multimedia .pptx
PPTX
fdokumen.com_array-2-dimensi-56874a32666b4.pptx
PPTX
Desain Multimedia Interaktif Kelas 12 SMK
PPTX
Streaming KD 3.5 Vektor.pptx
PPTX
Materi ajar fotografi.pptx
PPTX
PPT-UEU-Bahasa-Pemrograman-Pertemuan-9.pptx
PPT
Sequence Diagram.ppt
PPTX
Presentasi Best Practice.pptx
PPTX
Refleksi PPL 2 hudriyah.pptx
PPTX
Media ajar efek gambar vektor.pptx
PPTX
PJJ DMI Evaluasi Produk Web.pptx
PPTX
Desain Multimedia Interaktif KD 1 .pptx
522554777-Materi-4-karakter-Animasi-2d.pptx
project penguatan profil pelajar pancasila Suara Demokrasi.pptx
Sales Review NurHadi - April 2024.pptx
LAPORAN PRAKTEK-WPS Office mapel pilihan.pptx
mind mapping DKV mind mapping DKV mind mapping DKV
Desain Grafis Percetakan-Mengenal Fotografi
PBJ SMK 5 tgl 26-08-2024 .pptx
dmi kd 3.5 kelas XI Multimedia .pptx
fdokumen.com_array-2-dimensi-56874a32666b4.pptx
Desain Multimedia Interaktif Kelas 12 SMK
Streaming KD 3.5 Vektor.pptx
Materi ajar fotografi.pptx
PPT-UEU-Bahasa-Pemrograman-Pertemuan-9.pptx
Sequence Diagram.ppt
Presentasi Best Practice.pptx
Refleksi PPL 2 hudriyah.pptx
Media ajar efek gambar vektor.pptx
PJJ DMI Evaluasi Produk Web.pptx
Desain Multimedia Interaktif KD 1 .pptx
Ad

Recently uploaded (20)

PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
master seminar digital applications in india
PDF
RMMM.pdf make it easy to upload and study
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Pre independence Education in Inndia.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Cell Structure & Organelles in detailed.
PDF
Classroom Observation Tools for Teachers
PPTX
Pharma ospi slides which help in ospi learning
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
master seminar digital applications in india
RMMM.pdf make it easy to upload and study
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Types and Its function , kingdom of life
Pre independence Education in Inndia.pdf
Insiders guide to clinical Medicine.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Computing-Curriculum for Schools in Ghana
Module 4: Burden of Disease Tutorial Slides S2 2025
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Cell Structure & Organelles in detailed.
Classroom Observation Tools for Teachers
Pharma ospi slides which help in ospi learning
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
human mycosis Human fungal infections are called human mycosis..pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx

week14Pointers_II. pointers pemrograman dasar C++.pptx

  • 1. CSC113: COMPUTER PROGRAMMING (THEORY = 03, LAB = 01) Momina Moetesum Computer Science Department Bahria University, Islamabad
  • 3. 3 REFERENCE VARIABLES EXAMPLE #include <iostream.h> // Function prototypes (required in C++) void p_swap(int *, int *); void r_swap(int&, int&); int main (void){ int v = 5, x = 10; cout << v << x << endl; p_swap(&v,&x); cout << v << x << endl; r_swap(v,x); cout << v << x << endl; return 0; } void r_swap(int &a, int &b) { int temp; temp = a; (2) a = b; (3) b = temp; } void p_swap(int *a, int *b) { int temp; temp = *a; (2) *a = *b; (3) *b = temp; }
  • 4. 4 POINTER EXPRESSIONS AND POINTER ARITHMETIC  Pointer arithmetic  Increment/decrement pointer (++ or --)  Add/subtract an integer to/from a pointer( + or += , - or -=)  Pointers may be subtracted from each other  Pointer arithmetic is meaningless unless performed on an array  5 element int array on a machine using 4 byte ints  vPtr points to first element v[ 0 ], which is at location 3000  vPtr = 3000  vPtr += 2; sets vPtr to 3008  vPtr points to v[ 2 ] pointer variable vPtr v[0] v[1] v[2] v[4] v[3] 3000 3004 3008 3012 3016 location
  • 5. 5 POINTER EXPRESSIONS AND POINTER ARITHMETIC  Subtracting pointers  Returns the number of elements between two addresses vPtr2 = v[ 2 ]; vPtr = v[ 0 ]; vPtr2 - vPtr == 2  Pointer comparison  Test which pointer points to the higher numbered array element  Test if a pointer points to 0 (NULL) if ( vPtr == ‘0’ ) statement
  • 6. 6 VOID POINTER  Pointers assignment  If not the same type, a cast operator must be used  Exception: pointer to void (type void *)  Generic pointer, represents any type  No casting needed to convert a pointer to void pointer  void pointers cannot be dereferenced
  • 7. 7 THE RELATIONSHIP BETWEEN POINTERS AND ARRAYS  Arrays and pointers closely related  Array name like constant pointer  Pointers can do array subscripting operations  Having declared an array b[ 5 ] and a pointer bPtr  bPtr is equal to b bptr == b  bptr is equal to the address of the first element of b bptr == &b[ 0 ]
  • 8. 8 THE RELATIONSHIP BETWEEN POINTERS AND ARRAYS  Accessing array elements with pointers  Element b[ n ] can be accessed by *(bPtr + n)  Called pointer/offset notation  Array itself can use pointer arithmetic.  b[ 3 ] same as *(b + 3)  Pointers can be subscripted (pointer/subscript notation)  bPtr[ 3 ] same as b[ 3 ]
  • 9. EXAMPLE //using subscript and pointer notations with arrays #include<iostream> using namespace std; int main() { int b[]={10,20,30,40}; int *bPtr=b; cout<<“Array printed with:”<<endl; cout<<“ Array subscript notation” <<endl; for (int i=0; i<=3; i++) cout<<“b[”<<i<<“]=”<<b[i]<<endl; cout<<endl<<“Array/offset notation”<<endl; for(int offset=0;offset<=3;offset++) cout<<“*(b+”<<offset<<“)=” <<*(b+offset)<<endl; cout<<“ Pointer subscript notation” <<endl; for (int i=0; i<=3; i++) cout<<“bPtr[”<<i<<“]=”<<bPtr[i]<< endl; cout<<“Pointer/offset notation <<endl; for(int offset=0;offset<=3;offset++) cout<<“*(bPtr+”<<offset<<“)=”<< *(bPtr+offset)<<endl; return 0; }
  • 10. OUTPUT Array printed with Array subscript notation b[0]=10 b[1]=20 b[2]=30 b[3]=40 Pointer offset notation where the pointer is the array name *(b+0)=10 *(b+1)=20 *(b+2)=30 *(b+3)=40 Pointer subscript notation bPtr[0]=10 bPtr[1]=20 bPtr[2]=30 bPtr[3]=40 Pointer/offset notation *(bPtr+0)=10 *(bPtr+1)=20 *(bPtr+2)=30 *(bPtr+3)=40
  • 11. EXAMPLE //Copying a string using array notation and pointer notation #include<iostream> using namespace std; void copy1(char *, const char *); void copy2(char *, const char *); int main() { char string1[10], *string2=“Hello”; char string3[10],string4[]=“Good bye”; copy1(string1, string2); cout<<“string1=”<<string1<<endl; copy1(string3, string4); cout<<“string3=”<<string3<<endl; return 0; } //copy s2 and s1 using array notation void copy1(char *s1, const char *s2) { for(int i=0; (s1[i]=s2[i])!=‘0’;i++) ; //do nothing } //copy s2 and s1 using pointer notation void copy1(char *s1, const char *s2) { for( ; (*s1=*s2)!=‘0’; s1++,s2++) ; //do nothing }
  • 13. 13 ARRAYS OF POINTERS  Arrays can contain pointers  Commonly used to store an array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" };  Each element of suit is a pointer to a char * (a string)  The strings are not in the array, only pointers to the strings are in the array  suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’ 0’ ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’ 0’ ’C’ ’l’ ’u’ ’b’ ’s’ ’ 0’ ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’ 0’
  • 14. 14 CASE STUDY: A CARD SHUFFLING AND DEALING SIMULATION  Card shuffling program  Use an array of pointers to strings, to store suit names  Use a double scripted array (suit by value)  Place 1-52 into the array to specify the order in which the cards are dealt deck[2][12] represents the King of Clubs Hearts Diamonds Clubs Spades 0 1 2 3 Ace Two Three FourFive SixSeven Eight NineTen JackQueen King 0 1 2 3 4 5 6 7 8 9 10 11 12 Clubs King
  • 15. 15 FUNCTION POINTERS  Pointers to functions  Contain the address of the function  Similar to how an array name is the address of its first element  Function name is starting address of code that defines function  Function pointers can be  Passed to functions  Stored in arrays  Assigned to other function pointers
  • 16. 16 FUNCTION POINTERS  Example: bubblesort  Function bubble takes a function pointer  The function determines whether the the array is sorted into ascending or descending sorting  The argument in bubble for the function pointer bool ( *compare )( int, int ) tells bubble to expect a pointer to a function that takes two ints and returns a bool  If the parentheses were left out bool *compare( int, int ) would declare a function that receives two integers and returns a pointer to a bool
  • 17.  2000 Deitel & Associates, Inc.  2000 Deitel & Associates, Inc. Outline 1 // Fig. 5.26: fig05_26.cpp 2 // Multipurpose sorting program using function pointers 3 #include <iostream> 4 8 9 #include <iomanip> 10 12 13void bubble( int [], const int, bool (*)( int, int ) ); 14bool ascending( int, int ); 15bool descending( int, int ); 16 17int main() 18{ 19 const int arraySize = 10; 20 int order, 21 22 a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 23 24 cout << "Enter 1 to sort in ascending order,n" 25 << "Enter 2 to sort in descending order: "; 26 cin >> order; 27 cout << "nData items in original ordern"; 28 29 for ( counter = 0; counter < arraySize; counter++ ) 30 cout << setw( 4 ) << a[ counter ]; 31 32 if ( order == 1 ) { 33 bubble( a, arraySize, ascending ); 34 cout << "nData items in ascending ordern"; counter,
  • 18.  2000 Deitel & Associates, Inc.  2000 Deitel & Associates, Inc. Outline 35 } 36 else { 37 bubble( a, arraySize, descending ); 38 cout << "nData items in descending ordern"; 39 } 41 for ( counter = 0; counter < arraySize; counter++ ) 42 cout << setw( 4 ) << a[ counter ]; 44 cout << endl; 45 return 0; 46} 47 48void bubble( int work[], const int size, 49 bool (*compare)( int, int ) ) 50{ 51 void swap( int * const, int * const ); // prototype 52 53 for ( int pass = 1; pass < size; pass++ ) 55 for ( int count = 0; count < size - 1; count++ ) 57 if ( (*compare)( work[ count ], work[ count + 1 ] ) ) 58 swap( &work[ count ], &work[ count + 1 ] ); 59} 60 61void swap( int * const element1Ptr, int * const element2Ptr ) 62{ 63 int temp; 64 65 temp = *element1Ptr; 66 *element1Ptr = *element2Ptr; 67 *element2Ptr = temp;
  • 19.  2000 Deitel & Associates, Inc.  2000 Deitel & Associates, Inc. Outline Program output 69 70bool ascending( int a, int b ) 71{ 72 return b < a; // swap if b is less than a 73} 74 75bool descending( int a, int b ) 76{ 77 return b > a; // swap if b is greater than a 78} Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 1 Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 68 89 Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 2 Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in descending order 89 68 45 37 12 10 8 6 4 2
  • 20. 20 DYNAMIC MEMORY ALLOCATION  Dynamic Memory Allocation  The new operator  The delete operator  Dynamic Memory Allocation for Arrays
  • 21. 21 DYNAMIC MEMORY ALLOCATION  Static memory - where global and static variables live  Heap memory - dynamically allocated at execution time - "managed" memory accessed using pointers  Stack memory - used by automatic variables In C and C++, three types of memory are used by programs:
  • 22. 22 3 KINDS OF PROGRAM DATA  STATIC DATA: Allocated at compiler time  DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete  AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function
  • 23. 23 DYNAMIC MEMORY ALLOCATION  In C, functions such as malloc() are used to dynamically allocate memory from the Heap.  In C++, this is accomplished using the new and delete operators  new is used to allocate memory during execution time  returns a pointer to the address where the object is to be stored  always returns a pointer to the type that follows the new
  • 24. OPERATOR NEW SYNTAX new DataType new DataType [IntExpression]  If memory is available, in an area called the heap (or free store) new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated.  Otherwise, program terminates with error message.  The dynamically allocated object exists until the delete operator destroys it. 24
  • 25. 25 OPERATOR NEW char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ??? ptr 5000 5000 ‘B’
  • 26. OPERATOR DELETE SYNTAX delete Pointer delete [ ] Pointer  The object or array currently pointed to by Pointer is deallocated, and the value of Pointer is undefined. The memory is returned to the free store.  Good idea to set the pointer to the released memory to NULL  Square brackets are used with delete to deallocate a dynamically allocated array. 26
  • 27. 27 OPERATOR DELETE char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; 5000 5000 ‘B’ 2000 ptr ??? NOTE: delete deallocates the memory pointed to by ptr
  • 28. EXAMPLE #include <iostream> using namespace std; int main() { int n, *p, c; cout << "Enter an integern"; cin >> n; p = new int[n]; cout << "Enter " << n << " integersn"; for ( c = 0 ; c < n ; c++ ) cin >> p[c]; cout << "Elements entered by you aren"; for ( c = 0 ; c < n ; c++ ) cout << p[c] << endl; delete[] p; return 0; }