SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (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 a Chp3(pointers ref)

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.pptxsangeeta borde
 
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.pptxAnanthi Palanisamy
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfTamiratDejene1
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptchintuyadav19
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingAbdullah Jan
 
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 handlingRai University
 
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 handlingRai University
 
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 handlingRai University
 
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 handlingRai University
 
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 handlingRai University
 
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 handlingRai University
 
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 explainedhozaifafadl
 

Similar a 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
 

Último

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 

Último (20)

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 

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