SlideShare a Scribd company logo
1
int N = 26;
int *pN; // declare a pointer
pN = &N; // assign the address of N
A pointer variable is able to contain the address of some other variable. The
address-of operator (&) gets the address of a variable.
int * is a data type called pointer to integer.
2
26
N
29A6
pN
(Address 29A6)
pN points to N because pN contains N's address
Implementing a Pointer
3
double Z = 26;
int *pN;
pN = &Z; // compiler error
Pointer variables are strongly typed. In the following example, pN cannot point to Z
because Z is a double:
4
int N = 26;
int *pN = &N;
cout << *pN << endl; // "26"
The dereference operator (*) obtains the contents of the variable that is referenced
by a pointer.
5
int N = 26;
int *pN = &N;
*pN = 35;
cout << *pN << endl; // "35"
cout << N << endl; // "35"
The dereference operator can also be used to modify the contents of the referenced
variable.
Assigning a value to *pN changes the value of N.
6
int N = 26;
int *pN = &N;
int *pZ;
pZ = pN;
*pZ = 35; // now N = 35
One pointer may be assigned to another, as long as they point to the same type. In
this example, when pZ is dereferenced, it lets us change the value of N:
7
int N = 26;
int *pN = &N;
int Z = 0;
int *pZ = &Z;
*pZ = *pN; // Z = 26
Assigning a value from one pointer to another can be done by dereferencing both
pointers.
8
You can create pointers to any data type. A pointer to an object is dereferenced with
the -> operator when calling a member function.
9
#include <iostream>
#include <string.h>
using namespace std;
class Employee
{
private:
int id;
char name[60];
double Salary;
public:
Employee():id(0),name(""),Salary(0.0d)
{
cout<<"i am constructor"<<endl;
}
void GetData()
{
cout << "Enter Employee ID: ";
cin >> id;
cin.ignore();
cout << "Enter Employee Name: ";
cin.getline(name,60);
cout << "Enter Employee Salary: ";
cin >> Salary;
cin.ignore();
}
void Display()
{
cout << "The Employee ID: " << id << endl;
cout << "The Employee Name: " << name <<
endl;
cout << "The Employee Salary: " << Salary <<
endl ;
}
};
int main()
{
Employee obj;
Employee *ptremp = &obj;
//ptremp = &obj;
ptremp->GetData();
ptremp->Display();
return 0;
}
int n = 30;
int * p;
*p = n; // runtime error
Beware of dereferencing a pointer before it has been initialized. This causes a runtime
error (invalid pointer reference).
10
int * pN = NULL;
.
.
// ...later,
if( pN != NULL )
*pN = 35;
NULL is the best default value to assign to a pointer if you cannot assign it the address
of an object. A smart programmer will check for NULL before using the pointer.
11
• Use dynamic allocation to create an object at runtime. C++ uses the new operator.
• The object is stored in a large free memory area named the heap (or free store).
• The object remains on the heap either until you remove it or the program ends.
• The delete operator erases an object from the heap.
12
int * P = new int;
Create an int object on the heap and assign its address to P:
*P = 25; // assign a value
cout << *P << endl;
Use the pointer in the same way as previous examples:
13
Student * pS = new Student;
.
.
// use the student for a while...
.
.
delete pS; // gone!
The new operator returns the address of a new object. The delete operator erases the
object and makes it unavailable.
Student constructor called
14
void MySub()
{
Student * pS = new Student;
// use the Student for a while...
delete pS; // delete the Student
} // pS disappears
If you create an object inside a function, you may have to delete the object inside the
same function. In this example, variable pS goes out of scope at the end of the
function block.
15
void MySub()
{
Student * pS = new Student;
// use the Student for a while...
} // pS goes out of scope
(the Student's still left on the heap)
A memory leak is an error condition that is created when an object is left on the heap
with no pointer variable containing its address. This might happen if the object's
pointer goes out of scope:
16
Student * MakeStudent()
{
Student * pS = new Student;
return pS;
}
A function can return the address of an object that was created on the heap. In this
example, the function's return type is pointer to Student.
17
Student * pS;
pS = MakeStudent();
// now pS points to a Student
(continued)...
The caller of the function can receive the address and store it in a pointer variable. As
long as the pointer remains active, the Student object is accessible.
18
double * pD = new double;
*pD = 3.523;
.
.
delete pD; // pD is dangling...
.
.
*pD = 4.2; // error!
A dangling pointer is created when you delete its storage and then try to use the
pointer. It no longer points to valid storage and may corrupt the program's data.
19
delete pD;
pD = NULL;
.
.
if( pD != NULL ) // check it first...
*pD = 4.2;
To avoid using a dangling pointer, assign NULL to a pointer immediately after it is
deleted.
And, of course, check for NULL before using the pointer.
20
void swap( int * A, int * B )
{
int temp = *A;
*A = *B;
*B = temp;
}
Passing a pointer to a function is almost identical to passing by reference. The function
has read/write access to the data referenced by the pointer.
This is how swap() was written in C, before C++ introduced reference parameters:
21
void MySub( int * const A )
{
*A = 50; // ok
A++; // error
}
Declaring a constant pointer guarantees only that the pointer itself cannot be modified.
The data referenced by the pointer can still be modified.
22
Student * cop3337[10];
for(int i = 0; i < 10; i++)
{
cop3337[i] = new Student;
}
An array of pointers usually contains the addresses of dynamic data objects. This
keeps the storage used by the array itself quite small, and puts most of the data on the
heap.
diagram
23
Student
Student
Student
Student
Student
Student
Student
Student
Student
Student
Heap
cop3337 [ ]
Stack
24
void main()
{
double * samples = new double[10];
// samples is now an array....
samples[0] = 36.2;
delete [] samples;
}
You can create an entire array on the heap, using the new operator. Just remember to
delete it before the program exits. Include "[]" before the array name in the delete
statement.
array size
25
26

More Related Content

Similar to pointers.pptx

C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
HimanshuSharma997566
 
OOPS 22-23 (1).pptx
OOPS 22-23 (1).pptxOOPS 22-23 (1).pptx
OOPS 22-23 (1).pptx
SushmaGavaraskar
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
operator overloading
operator overloadingoperator overloading
operator overloading
Sorath Peetamber
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
ajajkhan16
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
janithlakshan1
 
Pointers
PointersPointers
Pointers
sanya6900
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
RashidFaridChishti
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Jayanshu Gundaniya
 
Oops presentation
Oops presentationOops presentation
Oops presentation
sushamaGavarskar1
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
AhalyaR
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
lodhran-hayat
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
Claus Wu
 
chapter-6 slide.pptx
chapter-6 slide.pptxchapter-6 slide.pptx
chapter-6 slide.pptx
cricketreview
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
naslin841216
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
aathmiboutique
 

Similar to pointers.pptx (20)

C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
OOPS 22-23 (1).pptx
OOPS 22-23 (1).pptxOOPS 22-23 (1).pptx
OOPS 22-23 (1).pptx
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Pointers
PointersPointers
Pointers
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Link list
Link listLink list
Link list
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
chapter-6 slide.pptx
chapter-6 slide.pptxchapter-6 slide.pptx
chapter-6 slide.pptx
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
 
Strctures,strings,pointers
Strctures,strings,pointersStrctures,strings,pointers
Strctures,strings,pointers
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
 

More from MuhammadAbubakar680442

Lecture 8 (1).pptx
Lecture 8 (1).pptxLecture 8 (1).pptx
Lecture 8 (1).pptx
MuhammadAbubakar680442
 
Lecture 8.pptx
Lecture 8.pptxLecture 8.pptx
Lecture 8.pptx
MuhammadAbubakar680442
 
verbs, regular irregular.pptx
verbs, regular irregular.pptxverbs, regular irregular.pptx
verbs, regular irregular.pptx
MuhammadAbubakar680442
 
ONTO ONE TO ONE FUNCTION.ppt
ONTO ONE TO ONE FUNCTION.pptONTO ONE TO ONE FUNCTION.ppt
ONTO ONE TO ONE FUNCTION.ppt
MuhammadAbubakar680442
 
Modal and Auxiliary Verbs.pptx
Modal and Auxiliary Verbs.pptxModal and Auxiliary Verbs.pptx
Modal and Auxiliary Verbs.pptx
MuhammadAbubakar680442
 
Lecture 14.pptx
Lecture 14.pptxLecture 14.pptx
Lecture 14.pptx
MuhammadAbubakar680442
 
onto into bijective.ppt
onto into bijective.pptonto into bijective.ppt
onto into bijective.ppt
MuhammadAbubakar680442
 
4.3e.pptx
4.3e.pptx4.3e.pptx

More from MuhammadAbubakar680442 (8)

Lecture 8 (1).pptx
Lecture 8 (1).pptxLecture 8 (1).pptx
Lecture 8 (1).pptx
 
Lecture 8.pptx
Lecture 8.pptxLecture 8.pptx
Lecture 8.pptx
 
verbs, regular irregular.pptx
verbs, regular irregular.pptxverbs, regular irregular.pptx
verbs, regular irregular.pptx
 
ONTO ONE TO ONE FUNCTION.ppt
ONTO ONE TO ONE FUNCTION.pptONTO ONE TO ONE FUNCTION.ppt
ONTO ONE TO ONE FUNCTION.ppt
 
Modal and Auxiliary Verbs.pptx
Modal and Auxiliary Verbs.pptxModal and Auxiliary Verbs.pptx
Modal and Auxiliary Verbs.pptx
 
Lecture 14.pptx
Lecture 14.pptxLecture 14.pptx
Lecture 14.pptx
 
onto into bijective.ppt
onto into bijective.pptonto into bijective.ppt
onto into bijective.ppt
 
4.3e.pptx
4.3e.pptx4.3e.pptx
4.3e.pptx
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 

pointers.pptx

  • 1. 1
  • 2. int N = 26; int *pN; // declare a pointer pN = &N; // assign the address of N A pointer variable is able to contain the address of some other variable. The address-of operator (&) gets the address of a variable. int * is a data type called pointer to integer. 2
  • 3. 26 N 29A6 pN (Address 29A6) pN points to N because pN contains N's address Implementing a Pointer 3
  • 4. double Z = 26; int *pN; pN = &Z; // compiler error Pointer variables are strongly typed. In the following example, pN cannot point to Z because Z is a double: 4
  • 5. int N = 26; int *pN = &N; cout << *pN << endl; // "26" The dereference operator (*) obtains the contents of the variable that is referenced by a pointer. 5
  • 6. int N = 26; int *pN = &N; *pN = 35; cout << *pN << endl; // "35" cout << N << endl; // "35" The dereference operator can also be used to modify the contents of the referenced variable. Assigning a value to *pN changes the value of N. 6
  • 7. int N = 26; int *pN = &N; int *pZ; pZ = pN; *pZ = 35; // now N = 35 One pointer may be assigned to another, as long as they point to the same type. In this example, when pZ is dereferenced, it lets us change the value of N: 7
  • 8. int N = 26; int *pN = &N; int Z = 0; int *pZ = &Z; *pZ = *pN; // Z = 26 Assigning a value from one pointer to another can be done by dereferencing both pointers. 8
  • 9. You can create pointers to any data type. A pointer to an object is dereferenced with the -> operator when calling a member function. 9 #include <iostream> #include <string.h> using namespace std; class Employee { private: int id; char name[60]; double Salary; public: Employee():id(0),name(""),Salary(0.0d) { cout<<"i am constructor"<<endl; } void GetData() { cout << "Enter Employee ID: "; cin >> id; cin.ignore(); cout << "Enter Employee Name: "; cin.getline(name,60); cout << "Enter Employee Salary: "; cin >> Salary; cin.ignore(); } void Display() { cout << "The Employee ID: " << id << endl; cout << "The Employee Name: " << name << endl; cout << "The Employee Salary: " << Salary << endl ; } }; int main() { Employee obj; Employee *ptremp = &obj; //ptremp = &obj; ptremp->GetData(); ptremp->Display(); return 0; }
  • 10. int n = 30; int * p; *p = n; // runtime error Beware of dereferencing a pointer before it has been initialized. This causes a runtime error (invalid pointer reference). 10
  • 11. int * pN = NULL; . . // ...later, if( pN != NULL ) *pN = 35; NULL is the best default value to assign to a pointer if you cannot assign it the address of an object. A smart programmer will check for NULL before using the pointer. 11
  • 12. • Use dynamic allocation to create an object at runtime. C++ uses the new operator. • The object is stored in a large free memory area named the heap (or free store). • The object remains on the heap either until you remove it or the program ends. • The delete operator erases an object from the heap. 12
  • 13. int * P = new int; Create an int object on the heap and assign its address to P: *P = 25; // assign a value cout << *P << endl; Use the pointer in the same way as previous examples: 13
  • 14. Student * pS = new Student; . . // use the student for a while... . . delete pS; // gone! The new operator returns the address of a new object. The delete operator erases the object and makes it unavailable. Student constructor called 14
  • 15. void MySub() { Student * pS = new Student; // use the Student for a while... delete pS; // delete the Student } // pS disappears If you create an object inside a function, you may have to delete the object inside the same function. In this example, variable pS goes out of scope at the end of the function block. 15
  • 16. void MySub() { Student * pS = new Student; // use the Student for a while... } // pS goes out of scope (the Student's still left on the heap) A memory leak is an error condition that is created when an object is left on the heap with no pointer variable containing its address. This might happen if the object's pointer goes out of scope: 16
  • 17. Student * MakeStudent() { Student * pS = new Student; return pS; } A function can return the address of an object that was created on the heap. In this example, the function's return type is pointer to Student. 17
  • 18. Student * pS; pS = MakeStudent(); // now pS points to a Student (continued)... The caller of the function can receive the address and store it in a pointer variable. As long as the pointer remains active, the Student object is accessible. 18
  • 19. double * pD = new double; *pD = 3.523; . . delete pD; // pD is dangling... . . *pD = 4.2; // error! A dangling pointer is created when you delete its storage and then try to use the pointer. It no longer points to valid storage and may corrupt the program's data. 19
  • 20. delete pD; pD = NULL; . . if( pD != NULL ) // check it first... *pD = 4.2; To avoid using a dangling pointer, assign NULL to a pointer immediately after it is deleted. And, of course, check for NULL before using the pointer. 20
  • 21. void swap( int * A, int * B ) { int temp = *A; *A = *B; *B = temp; } Passing a pointer to a function is almost identical to passing by reference. The function has read/write access to the data referenced by the pointer. This is how swap() was written in C, before C++ introduced reference parameters: 21
  • 22. void MySub( int * const A ) { *A = 50; // ok A++; // error } Declaring a constant pointer guarantees only that the pointer itself cannot be modified. The data referenced by the pointer can still be modified. 22
  • 23. Student * cop3337[10]; for(int i = 0; i < 10; i++) { cop3337[i] = new Student; } An array of pointers usually contains the addresses of dynamic data objects. This keeps the storage used by the array itself quite small, and puts most of the data on the heap. diagram 23
  • 25. void main() { double * samples = new double[10]; // samples is now an array.... samples[0] = 36.2; delete [] samples; } You can create an entire array on the heap, using the new operator. Just remember to delete it before the program exits. Include "[]" before the array name in the delete statement. array size 25
  • 26. 26