SlideShare a Scribd company logo
1 of 19
Pointers
   and
References
OBJECTIVES
• To understand the differences between
  C and C++ pointers
• To be able to use references as
  independent variables and function
  parameters
• To be able to use pointers and
  references with constants
INTRODUCTION
• C pointers are very powerful. If not used
  properly, prone produce unpredictable
  results, system clashes.
• C++ enhances C pointers, provides increases
  security because of its rigidity.
• References have advantages over regular
  pointers when passed to functions.
C++ POINTERS
REVIEWING THE FUNDAMENTALS
          OF POINTERS
• A pointer : variable used to store a memory
  address.
• The address : location of one of the following in
  memory:-
  - variable, pointer, function
• Major benefits:
  - support dynamic memory allocation
  - functions can modify actual arguments
  - support data structures : linked-list, binary trees
  - improve efficiency of some programs
• To avoid system crashes, use pointers correctly!
Data_type           *variable_name;
•   int *ptr1;       //point to any variable of type integer
•   double *ptr2;    //point to any variable of type double
•   void *ptr3;     //point to a variable of any type
•   Robot *ptr4;    //point to any variable of user-
                      defined type named Robot.

(*) indirection operator
        (&) address-of operator
• & returns memory address of its operand
• * precedes a pointer and returns the value of a
  variable, the address of which is stored in the pointer
•   float x = 1.23, y;
•   float *pt;    //pt can point to any variable of type float
•   pt=&x;        //places the memory address of x into pt
•   cout<<*pt; //prints the value of x : 1.23
• * (access value the pointer points to) - dereferencing the pointer.
• A void pointer cannot be dereferenced.
•   void *pt1;          //pt1 is a void pointer
•   int *pt2;          //pt2 is an integer pointer
•   int x = 3, y, z;
•   pt1 = pt2 = &x;            //pt1, pt2 point to x
•   y=*pt1;          //Error! pt1 cannot be dereferenced
•   z=*pt2;          //Correct! pt2 is dereferenced.Value of x is
                        placed into z
• Pointers can be used as operands in assignments,
  arithmetic, comparison expressions.
• float f=13.3; //Assume: address of f is 1000 and size of float is 8 bytes.
• float *ptr1, *ptr2;       ptr1 = &f;
• ptr2=ptr1;      //Assigning pointers: ptr1 and ptr2 point to f
• ptr1--;         //Decrementing ptr1
• cout<<ptr1; //value of ptr1 is 992 (=1000-8)
• ptr2=ptr2+5; //adding 5 to ptr2 and assigning result to
                    ptr2
• cout<<ptr2; //value of ptr2 is 1040 (=1000+5*8)
• if (ptr1==ptr2) //comparing pointers by equality
      cout<<“Both pointers contain same memory
               address.”;
A pointer can point to another pointer

•   float a=0.99, *b, **c;
•   b=&a;        //pointer b points to pointer a
•   c=&b;       //pointer c points to pointer b
•   cout<<**c; //deferencing pointer c two times to access a


When declaring a pointer that points to another pointer,
    2 asterisks must precede the pointer name
Array
• Array elements can also be accessed using
  pointers.
• Array name returns starting address of the
  array (address of 1st element of array)
• Array name can also be used as a pointer
  to the array.
• There are 2 different ways of accessing
  array elements.
• Accessing array elements using pointers
  can be faster than array indexing.
//Array declaration:

• int array[5] = {1,2,3,4,5};

//Accessing array elements:

Array-indexing         Pointer notation
array[0]               *array             1st element
array[1]               *(array+1)         2nd element
array[2]               *(array+2)         3rd element
array[3]               *(array+3)         4th element
array[4]               *(array+4)         5th element
String
• A string is equivalent to a character pointer.
• Operations with strings are often performed by using
  pointers.
•   char scientist[13] = “Nikola Tesla”
•   char *cptr;
•   cptr=scientist; //cptr is set to the address of scientist
•   cout<<*(cptr+2); //prints the 3rd character of?
•   cout<<cptr; //prints the ?
REFERENCES
• C++ provides new kinds of variables called
  references
• Acts as alternatives names for other variable
• Can be used in 3 different ways:
  - independent variable
  - passed to a function
  - returned by a function
• Passing references between function is a
  powerful and very important use of
  references.
REFERENCES
                    as
           Independent Variables

• Data_type & reference_name = variable_name

 float num = 7.3;
 float & refnum = num;
                //No & before num
                //space between & and refnum: optional
Differences between Pointers
             and References
RESTRICTIONS                                   Reference Pointer
It reserves a space in the memory to store     NO        YES
an address that it points to or references.
It has to be initialized when it is declared   YES       NO
It can be initialized at any time              NO        YES
Once it is initialized, it can be changed to   NO        YES
point to another variable of the same type
It has to be dereferenced to get to a value    NO        YES
it points to
It can be a NULL pointer/reference             NO        YES
It can point to another reference/pointer      NO        YES
An array of references/pointers can be         NO        YES
created
• Because of the practical reasons and
  restrictions mentioned in previous, most
  programmers feel that there is no
  reason to use references as
  independent variables.

• They can also add complexity to a
  program.
Quiz
//Program demonstrates a use of an independent reference variable.


int main()
{
   int i = 13;
   int &iref = i;
   cout<<“The value is => “<<iref;
   i--;
   cout<<“nAfter decrementing => “<<iref<<endl;
   iref = 99;
   cout<<“The value is now => “<<i;
   return 0;
}
Lab Work
• Passing references to functions
• Returning references by functions


             Next Class
• Using references and pointers with
  constants
• Dynamic memory allocation

More Related Content

What's hot

Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
tech4us
 
Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppt
eShikshak
 
Pointers in c
Pointers in cPointers in c
Pointers in c
Mohd Arif
 

What's hot (18)

Pointers
PointersPointers
Pointers
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Computer Science:Pointers in C
Computer Science:Pointers in CComputer Science:Pointers in C
Computer Science:Pointers in C
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppt
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Ponters
PontersPonters
Ponters
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers In C
Pointers In CPointers In C
Pointers In C
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointer in c++ part1
Pointer in c++ part1Pointer in c++ part1
Pointer in c++ part1
 

Similar to Chp3(pointers ref)

Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptx
Ananthi Palanisamy
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 

Similar to Chp3(pointers ref) (20)

pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Lab 3.pptx
Lab 3.pptxLab 3.pptx
Lab 3.pptx
 
Lab 3.pptx
Lab 3.pptxLab 3.pptx
Lab 3.pptx
 
Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptx
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ Programming
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Session 5
Session 5Session 5
Session 5
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Pointers
PointersPointers
Pointers
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Chp3(pointers ref)

  • 1. Pointers and References
  • 2. OBJECTIVES • To understand the differences between C and C++ pointers • To be able to use references as independent variables and function parameters • To be able to use pointers and references with constants
  • 3. INTRODUCTION • C pointers are very powerful. If not used properly, prone produce unpredictable results, system clashes. • C++ enhances C pointers, provides increases security because of its rigidity. • References have advantages over regular pointers when passed to functions.
  • 5. REVIEWING THE FUNDAMENTALS OF POINTERS • A pointer : variable used to store a memory address. • The address : location of one of the following in memory:- - variable, pointer, function • Major benefits: - support dynamic memory allocation - functions can modify actual arguments - support data structures : linked-list, binary trees - improve efficiency of some programs • To avoid system crashes, use pointers correctly!
  • 6. Data_type *variable_name; • int *ptr1; //point to any variable of type integer • double *ptr2; //point to any variable of type double • void *ptr3; //point to a variable of any type • Robot *ptr4; //point to any variable of user- defined type named Robot. (*) indirection operator (&) address-of operator • & returns memory address of its operand • * precedes a pointer and returns the value of a variable, the address of which is stored in the pointer
  • 7. float x = 1.23, y; • float *pt; //pt can point to any variable of type float • pt=&x; //places the memory address of x into pt • cout<<*pt; //prints the value of x : 1.23 • * (access value the pointer points to) - dereferencing the pointer. • A void pointer cannot be dereferenced. • void *pt1; //pt1 is a void pointer • int *pt2; //pt2 is an integer pointer • int x = 3, y, z; • pt1 = pt2 = &x; //pt1, pt2 point to x • y=*pt1; //Error! pt1 cannot be dereferenced • z=*pt2; //Correct! pt2 is dereferenced.Value of x is placed into z
  • 8. • Pointers can be used as operands in assignments, arithmetic, comparison expressions. • float f=13.3; //Assume: address of f is 1000 and size of float is 8 bytes. • float *ptr1, *ptr2; ptr1 = &f; • ptr2=ptr1; //Assigning pointers: ptr1 and ptr2 point to f • ptr1--; //Decrementing ptr1 • cout<<ptr1; //value of ptr1 is 992 (=1000-8) • ptr2=ptr2+5; //adding 5 to ptr2 and assigning result to ptr2 • cout<<ptr2; //value of ptr2 is 1040 (=1000+5*8) • if (ptr1==ptr2) //comparing pointers by equality cout<<“Both pointers contain same memory address.”;
  • 9. A pointer can point to another pointer • float a=0.99, *b, **c; • b=&a; //pointer b points to pointer a • c=&b; //pointer c points to pointer b • cout<<**c; //deferencing pointer c two times to access a When declaring a pointer that points to another pointer, 2 asterisks must precede the pointer name
  • 10. Array • Array elements can also be accessed using pointers. • Array name returns starting address of the array (address of 1st element of array) • Array name can also be used as a pointer to the array. • There are 2 different ways of accessing array elements. • Accessing array elements using pointers can be faster than array indexing.
  • 11. //Array declaration: • int array[5] = {1,2,3,4,5}; //Accessing array elements: Array-indexing Pointer notation array[0] *array 1st element array[1] *(array+1) 2nd element array[2] *(array+2) 3rd element array[3] *(array+3) 4th element array[4] *(array+4) 5th element
  • 12. String • A string is equivalent to a character pointer. • Operations with strings are often performed by using pointers. • char scientist[13] = “Nikola Tesla” • char *cptr; • cptr=scientist; //cptr is set to the address of scientist • cout<<*(cptr+2); //prints the 3rd character of? • cout<<cptr; //prints the ?
  • 14. • C++ provides new kinds of variables called references • Acts as alternatives names for other variable • Can be used in 3 different ways: - independent variable - passed to a function - returned by a function • Passing references between function is a powerful and very important use of references.
  • 15. REFERENCES as Independent Variables • Data_type & reference_name = variable_name float num = 7.3; float & refnum = num; //No & before num //space between & and refnum: optional
  • 16. Differences between Pointers and References RESTRICTIONS Reference Pointer It reserves a space in the memory to store NO YES an address that it points to or references. It has to be initialized when it is declared YES NO It can be initialized at any time NO YES Once it is initialized, it can be changed to NO YES point to another variable of the same type It has to be dereferenced to get to a value NO YES it points to It can be a NULL pointer/reference NO YES It can point to another reference/pointer NO YES An array of references/pointers can be NO YES created
  • 17. • Because of the practical reasons and restrictions mentioned in previous, most programmers feel that there is no reason to use references as independent variables. • They can also add complexity to a program.
  • 18. Quiz //Program demonstrates a use of an independent reference variable. int main() { int i = 13; int &iref = i; cout<<“The value is => “<<iref; i--; cout<<“nAfter decrementing => “<<iref<<endl; iref = 99; cout<<“The value is now => “<<i; return 0; }
  • 19. Lab Work • Passing references to functions • Returning references by functions Next Class • Using references and pointers with constants • Dynamic memory allocation