SlideShare a Scribd company logo
1 of 42
Object Oriented Programming using C++

          Pointers overview


              Lecture 17
What is a Pointer?

•   A P o i n t e r provides a way of accessing a variable without
    referring to the variable directly.

•   The m e c h a n i s m used for this purpose is the address of
    the variable.

•   A variable that stores the address of another variable is called
    a p o in t e r v a r ia b l e .
Pointer Variables

•   Pointer variable (pointer): variable that holds an address

•   Can perform some tasks more easily with an address than by
    accessing memory via a symbolic name:
     – Accessing unnamed memory locations
     – Array manipulation
     – etc.
Why Use Pointers?
•   To operate on data stored in an array

•   To enable convenient access within a function to large blocks
    data, such as arrays, that are defined outside the function.

•   To allocate space for new variables d y n a mic a l l y – that
    is during program execution
Using Pointers

• To use a pointer we need to
   – Store the address of another variable of the appropriate
     type in it.

• How       w e o b t a in t h e a d d r e s s o f
  a v a r ia b le
Pointer Data Types and Pointer
                  Variables
• Pointer variable: variable whose content is a memory address
• Syntax to declare pointer variable:
   dataType *identifier;
• Address of operator: Ampersand, &
• Dereferencing operator/Indirection operator:
  Asterisk, *
T h e Address-Of O p e r a t o r (&)

•   The address-of operator, & , is a unary operator that obtains
    the address in memory where a variable is stored.
     i n t n u m b e r = 12 3 4 ;
     i n t * p n u m b e r = & n u m b e r ; / stores address of
                                              /
                                 / number in pnumber
                                  /
    c ha r a = ‘ a ’ ;
    c h a r *p a = & a ;             / stores address of a in pa.
                                      /
The Indirection Operator

•   H o w p o in t e r v a r ia b le is u s e d t o
    a c c e s s the c o nte nts o f me mo ry
    lo c a t io n ?

•   The i n d i r e c t i o n o p e r a t o r , * is used for this
    purpose.
    ----
    c o u t << * p n u m b e r ;
The Indirection Operator

int x= 4;

int *px = &x;         //stores address of variable x in variable px

            Add re                  Add re
                                    s ses
                                             cout<<“The number is:”<<x;
            s ses
                        x    4      13 1
                                             The output is:
x     4     13 1
                                     0
             0
                                    13 1
            13 1
             2
                        p   13 10
                                     2
                                    13 1
                                             The number is: 4
            13 1
                        x            4
             4
                                    13 1
            13 1
                                     6
             6



 cout<<“The number accessed by pointer variable is: ”<<*px
  T he output is:
    The number is: 4
The Indirection Operator

 int x= 4;

    int *px = &x; //stores address of variable x in variable px

                                      Ad dre s s
                                         es

                         x      43     13 1
                                        0

                                       13 1
                                        2

                         p    13 10    13 1
                         x              4

                                       13 1
                                        6




*px = 3      / T his statement means assign 3 to a variable “p o in t e d t o ” by p x .
              /

The data is accessed indirectly
pointer


int x = 10;
int *p;                 p

p = &x;                              10   x




p gets the address of x in memory.
What is a pointer?


int x = 10;
int *p;                  p

p = &x;                             20   x

*p = 20;


*p is the value at the address p.
What is a pointer?

                   Declares a pointer
int x = 10;        to an integer
int *p;

p = &x;           & is address operator
                    gets address of x
*p = 20;

             * dereference operator
               gets value at p
Pointers



• Statements:
  int *p;
  int num;
Pointers
Pointers
Pointers
Pointers

• Summary of preceding diagrams
   –   &p, p, and *p all have different meanings
   –   &p means the address of p
   –   p means the content of p
   –   *p means the content pointed to by p, that is pointed to by the
       content of memory location
Pointers
Getting the Address of a Variable
• Each variable in program is stored at a unique address
• Use address operator & to get address of a variable:
     int num = -23;
     cout << &num;



                                  // prints address
                                  // in hexadecimal
Pointer Variables

• Definition:
     int   *intptr;
• Read as:
  “intptr can hold the address of an int”
• Spacing in definition does not matter:
     int *intptr; // same as above
     int* intptr; // same as above
Pointer Variables

• Assignment:
   int *intptr;
   intptr = &num;
• Memory layout:

                        num              intptr
                        25               0x4a00
• Can access num using intptr and indirection operator *:
     address of num: 0x4a00
      cout << *intptr << endl;
Assigning a value to a dereferenced pointer



A pointer must have a value before you can dereference it
   (follow the pointer).


   int *x;                            int foo;
   *x=3;                              int *x;
                                      x = &foo;
                         ing!!!
      R!!!       o anyth              *x=3;
ERRO n’t point t
     s
x doe                                                  e
                                                 is fin foo
                                            this         o
                                             x po ints t
Pointers to anything

                            x       some int
int *x;
int **y;
               y     some *int      some int


double *z;
                        z        some double
The Relationship Between Arrays and Pointers


• Array name is starting address of array
     int vals[] = {4, 7, 11};
  starting address of vals: 0x4a00    4     7   11



     cout << vals;                   // displays 0x4a00

     cout << vals[0];
                                      // displays 4
Pointers and Arrays

• An array name is basically a const pointer.
• You can use the [] operator with a pointer:

   int *x;
   int a[10];
   x = &a[2];                    x is “the address of a[2] ”
Pointer Arithmetic


  • Operations on pointer variables:
Operation                      Example
                               int vals[]={4,7,11};
                               int *valptr = vals;
++, --                         valptr++; // points at 7
                               valptr--; // now points at 4
+, - (pointer and int)         cout << *(valptr + 2); // 11

+=, -= (pointer                valptr = vals; // points at 4
and int)                       valptr += 2;   // points at 11
- (pointer from pointer)       cout << valptr–val; // difference
                               //(number of ints) between valptr
                               // and val
Pointer arithmetic
• Integer math operations can be used with pointers.
• If you increment a pointer, it will be increased by the size
  of whatever it points to.




   int *ptr = a;
                        *(ptr+2)
                                            *(ptr+4)
        *ptr


       a[0]     a[1]    a[2]     a[3]    a[4]

                    int a[5];
Initializing Pointers

• Can initialize at definition time:
     int num, *numptr = &num;
     int val[3], *valptr = val;


• Cannot mix data types:
     float cost;
     int *ptr = &cost; // won’t work
Comparing Pointers

• Relational operators (<, >=, etc.) can be used to
  compare addresses in pointers
• Comparing addresses in pointers is not the same as
  comparing contents pointed at by pointers:
     if (ptr1 == ptr2)   // compares
                                // addresses
     if (*ptr1 == *ptr2) // compares
                              // contents
Allocating memory using n e w

Point *p = new Point(5, 5);

•   new can be thought of a function with slightly strange syntax
•   new allocates space to hold the object.
•   new calls the object’s constructor.
•   new returns a pointer to that object.
Deallocating memory using d e l e t e

// allocate memory
Point *p = new Point(5, 5);
...
// free the memory
delete p;

For every call to new, there must be
exactly one call to delete.
Dynamic Memory Allocation

• DMA provides a mechanism to allocate memory at run-time by the
  programmer
• Memory Free Store
   – During execution of program, there is unused memory in the
     computer. It is called free store.
• Dynamic Storage duration
   – Life-span of dynamic variables is defined by the programmer
• The Operators new and delete are used for DMA
Rules to Observe

• Do not use delete to free the memory not allocated by new
• Do not use delete to free the same block of memory twice
  in succession
• Use delete [ ] if you used new to allocate memory for an
  array
Void Pointer

• A void* is a generic pointer. Pointer of any type can be assigned to the
  void pointer
• Once assigned the type of void* is the same as that of assigned pointer
  type
• Dereferencing a void* is a syntax error
    void* sPtr; int num;
    int z[3]={1,2,3};
    sPtr= z;
    num= *sPtr; // ERROR
    num= *(int*) sPtr; // correct version
Functions
• Pass by value
   – A copy of argument it created
   – The value of the passed argument is not modified
   – The operation is performed on the copy of passed value as
     argument
• Pass by reference
   – The address of argument is passed
   – The value of the passed argument gets modified
   – This may occur by Reference variable or through pointer
     variables
Pointer Parameters
• Pointers are passed by value (the value of a pointer is
  the address it holds).

• If we change what the pointer points to the caller will
  see the change.

• If we change the pointer itself, the caller won't see the
  change (we get a copy of the pointer)
Pointers as Function Parameters
•   A pointer can be parameter
•   Works like reference variable to allow change to argument from within
    function
•   Requires:
    –    asterisk * on parameter in prototype and heading
    void getNum(int*);            // function prototype
    void getNum(int *ptr) // function header
                                  // ptr is pointer to an int
    –   asterisk * in body to dereference the pointer
     cin >> *ptr;
    –   address as argument to the function
    getNum(&num);         // pass address of num to getNum
Pointers as Function Parameters

void swap(int *x, int *y)
{     int temp;
      temp = *x;
      *x = *y;
      *y = temp;
}

int num1 = 2, num2 = -3;
swap(&num1, &num2);
Passing pointers as arguments
 When a pointer is passed as an argument, it divulges an address to
 the called function, so the function can change the value stored at
 that address:
   void passPointer(int* iPtr){
     *iPtr += 2;         // note *iPtr on left!
   }
   ...
   int i = 3;
   int* iPtr = &i;
   passPointer(iPtr);
   cout << "i = " << i << endl;     // prints i = 5
   passPointer(&i);             // equivalent to above
   cout << "i = " << i << endl;     // prints i = 7
 End result same as pass-by-reference, syntax different. (Usually
 pass by reference is the preferred technique.)
Glen Cowan
RHUL Physics                                     Computing and Statistical Data Analysis
Pointers vs. reference variables

  A reference variable behaves like an alias for a regular variable.
  To declare, place & after the type:
    void passReference(int& i){
      i += 2;
    }

    ...
    int i = 3;
    int& j = i;        // j is a reference variable
    j = 7;
    cout << "i = " << i << endl; // prints i = 7
    passReference(j);
    cout << "i = " << i << endl; // prints i = 9

   Passing a reference variable to a function is the same as
   passing a normal variable by reference.
Glen Cowan
RHUL Physics                                       Computing and Statistical Data Analysis
What to do with pointers

  You can do lots of things with pointers in C++, many of
  which result in confusing code and hard-to-find bugs.
  One of the main differences between Java and C++: Java doesn’t
  have pointer variables (generally seen as a Good Thing).
  To learn about “pointer arithmetic” and other dangerous
  activities, consult most C++ books; we will not go into it here.
  The main usefulness of pointers for us is that they will allow
  us to allocate memory (create variables) dynamically, i.e., at
  run time, rather than at compile time.



Glen Cowan
RHUL Physics                                      Computing and Statistical Data Analysis

More Related Content

What's hot

Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Ali Aminian
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - PointersWingston
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in Crgnikate
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++Ilio Catallo
 
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
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 

What's hot (20)

Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Pointer in c++ part1
Pointer in c++ part1Pointer in c++ part1
Pointer in c++ part1
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Pointers_c
Pointers_cPointers_c
Pointers_c
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
C++ Chapter IV
C++ Chapter IVC++ Chapter IV
C++ Chapter IV
 
C++ Chapter III
C++ Chapter IIIC++ Chapter III
C++ Chapter III
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Ponters
PontersPonters
Ponters
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
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...
 
See through C
See through CSee through C
See through C
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 

Similar to oop Lecture 17

Similar to oop Lecture 17 (20)

Pointer
PointerPointer
Pointer
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
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
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
C Pointers
C PointersC Pointers
C Pointers
 
Pointer
PointerPointer
Pointer
 
Pointer
PointerPointer
Pointer
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
 
Pointers
PointersPointers
Pointers
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Pointers
PointersPointers
Pointers
 
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
 

More from Anwar Ul Haq

More from Anwar Ul Haq (12)

oop Lecture19
oop Lecture19oop Lecture19
oop Lecture19
 
oop Lecture 16
oop Lecture 16oop Lecture 16
oop Lecture 16
 
oop Lecture 11
oop Lecture 11oop Lecture 11
oop Lecture 11
 
oop Lecture 10
oop Lecture 10oop Lecture 10
oop Lecture 10
 
oop Lecture 9
oop Lecture 9oop Lecture 9
oop Lecture 9
 
oop Lecture 7
oop Lecture 7oop Lecture 7
oop Lecture 7
 
oop Lecture 6
oop Lecture 6oop Lecture 6
oop Lecture 6
 
oop Lecture 5
oop Lecture 5oop Lecture 5
oop Lecture 5
 
oop Lecture 4
oop Lecture 4oop Lecture 4
oop Lecture 4
 
oop Lecture 3
oop Lecture 3oop Lecture 3
oop Lecture 3
 
Oop lec 2
Oop lec 2Oop lec 2
Oop lec 2
 
Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Object Oriented Programming lecture 1
Object Oriented Programming lecture 1
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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 MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

oop Lecture 17

  • 1. Object Oriented Programming using C++ Pointers overview Lecture 17
  • 2. What is a Pointer? • A P o i n t e r provides a way of accessing a variable without referring to the variable directly. • The m e c h a n i s m used for this purpose is the address of the variable. • A variable that stores the address of another variable is called a p o in t e r v a r ia b l e .
  • 3. Pointer Variables • Pointer variable (pointer): variable that holds an address • Can perform some tasks more easily with an address than by accessing memory via a symbolic name: – Accessing unnamed memory locations – Array manipulation – etc.
  • 4. Why Use Pointers? • To operate on data stored in an array • To enable convenient access within a function to large blocks data, such as arrays, that are defined outside the function. • To allocate space for new variables d y n a mic a l l y – that is during program execution
  • 5. Using Pointers • To use a pointer we need to – Store the address of another variable of the appropriate type in it. • How w e o b t a in t h e a d d r e s s o f a v a r ia b le
  • 6. Pointer Data Types and Pointer Variables • Pointer variable: variable whose content is a memory address • Syntax to declare pointer variable: dataType *identifier; • Address of operator: Ampersand, & • Dereferencing operator/Indirection operator: Asterisk, *
  • 7. T h e Address-Of O p e r a t o r (&) • The address-of operator, & , is a unary operator that obtains the address in memory where a variable is stored. i n t n u m b e r = 12 3 4 ; i n t * p n u m b e r = & n u m b e r ; / stores address of / / number in pnumber / c ha r a = ‘ a ’ ; c h a r *p a = & a ; / stores address of a in pa. /
  • 8. The Indirection Operator • H o w p o in t e r v a r ia b le is u s e d t o a c c e s s the c o nte nts o f me mo ry lo c a t io n ? • The i n d i r e c t i o n o p e r a t o r , * is used for this purpose. ---- c o u t << * p n u m b e r ;
  • 9. The Indirection Operator int x= 4; int *px = &x; //stores address of variable x in variable px Add re Add re s ses cout<<“The number is:”<<x; s ses x 4 13 1 The output is: x 4 13 1 0 0 13 1 13 1 2 p 13 10 2 13 1 The number is: 4 13 1 x 4 4 13 1 13 1 6 6 cout<<“The number accessed by pointer variable is: ”<<*px T he output is: The number is: 4
  • 10. The Indirection Operator int x= 4; int *px = &x; //stores address of variable x in variable px Ad dre s s es x 43 13 1 0 13 1 2 p 13 10 13 1 x 4 13 1 6 *px = 3 / T his statement means assign 3 to a variable “p o in t e d t o ” by p x . / The data is accessed indirectly
  • 11. pointer int x = 10; int *p; p p = &x; 10 x p gets the address of x in memory.
  • 12. What is a pointer? int x = 10; int *p; p p = &x; 20 x *p = 20; *p is the value at the address p.
  • 13. What is a pointer? Declares a pointer int x = 10; to an integer int *p; p = &x; & is address operator gets address of x *p = 20; * dereference operator gets value at p
  • 14. Pointers • Statements: int *p; int num;
  • 18. Pointers • Summary of preceding diagrams – &p, p, and *p all have different meanings – &p means the address of p – p means the content of p – *p means the content pointed to by p, that is pointed to by the content of memory location
  • 20. Getting the Address of a Variable • Each variable in program is stored at a unique address • Use address operator & to get address of a variable: int num = -23; cout << &num; // prints address // in hexadecimal
  • 21. Pointer Variables • Definition: int *intptr; • Read as: “intptr can hold the address of an int” • Spacing in definition does not matter: int *intptr; // same as above int* intptr; // same as above
  • 22. Pointer Variables • Assignment: int *intptr; intptr = &num; • Memory layout: num intptr 25 0x4a00 • Can access num using intptr and indirection operator *: address of num: 0x4a00 cout << *intptr << endl;
  • 23. Assigning a value to a dereferenced pointer A pointer must have a value before you can dereference it (follow the pointer). int *x; int foo; *x=3; int *x; x = &foo; ing!!! R!!! o anyth *x=3; ERRO n’t point t s x doe e is fin foo this o x po ints t
  • 24. Pointers to anything x some int int *x; int **y; y some *int some int double *z; z some double
  • 25. The Relationship Between Arrays and Pointers • Array name is starting address of array int vals[] = {4, 7, 11}; starting address of vals: 0x4a00 4 7 11 cout << vals; // displays 0x4a00 cout << vals[0]; // displays 4
  • 26. Pointers and Arrays • An array name is basically a const pointer. • You can use the [] operator with a pointer: int *x; int a[10]; x = &a[2]; x is “the address of a[2] ”
  • 27. Pointer Arithmetic • Operations on pointer variables: Operation Example int vals[]={4,7,11}; int *valptr = vals; ++, -- valptr++; // points at 7 valptr--; // now points at 4 +, - (pointer and int) cout << *(valptr + 2); // 11 +=, -= (pointer valptr = vals; // points at 4 and int) valptr += 2; // points at 11 - (pointer from pointer) cout << valptr–val; // difference //(number of ints) between valptr // and val
  • 28. Pointer arithmetic • Integer math operations can be used with pointers. • If you increment a pointer, it will be increased by the size of whatever it points to. int *ptr = a; *(ptr+2) *(ptr+4) *ptr a[0] a[1] a[2] a[3] a[4] int a[5];
  • 29. Initializing Pointers • Can initialize at definition time: int num, *numptr = &num; int val[3], *valptr = val; • Cannot mix data types: float cost; int *ptr = &cost; // won’t work
  • 30. Comparing Pointers • Relational operators (<, >=, etc.) can be used to compare addresses in pointers • Comparing addresses in pointers is not the same as comparing contents pointed at by pointers: if (ptr1 == ptr2) // compares // addresses if (*ptr1 == *ptr2) // compares // contents
  • 31. Allocating memory using n e w Point *p = new Point(5, 5); • new can be thought of a function with slightly strange syntax • new allocates space to hold the object. • new calls the object’s constructor. • new returns a pointer to that object.
  • 32. Deallocating memory using d e l e t e // allocate memory Point *p = new Point(5, 5); ... // free the memory delete p; For every call to new, there must be exactly one call to delete.
  • 33. Dynamic Memory Allocation • DMA provides a mechanism to allocate memory at run-time by the programmer • Memory Free Store – During execution of program, there is unused memory in the computer. It is called free store. • Dynamic Storage duration – Life-span of dynamic variables is defined by the programmer • The Operators new and delete are used for DMA
  • 34. Rules to Observe • Do not use delete to free the memory not allocated by new • Do not use delete to free the same block of memory twice in succession • Use delete [ ] if you used new to allocate memory for an array
  • 35. Void Pointer • A void* is a generic pointer. Pointer of any type can be assigned to the void pointer • Once assigned the type of void* is the same as that of assigned pointer type • Dereferencing a void* is a syntax error void* sPtr; int num; int z[3]={1,2,3}; sPtr= z; num= *sPtr; // ERROR num= *(int*) sPtr; // correct version
  • 36. Functions • Pass by value – A copy of argument it created – The value of the passed argument is not modified – The operation is performed on the copy of passed value as argument • Pass by reference – The address of argument is passed – The value of the passed argument gets modified – This may occur by Reference variable or through pointer variables
  • 37. Pointer Parameters • Pointers are passed by value (the value of a pointer is the address it holds). • If we change what the pointer points to the caller will see the change. • If we change the pointer itself, the caller won't see the change (we get a copy of the pointer)
  • 38. Pointers as Function Parameters • A pointer can be parameter • Works like reference variable to allow change to argument from within function • Requires: – asterisk * on parameter in prototype and heading void getNum(int*); // function prototype void getNum(int *ptr) // function header // ptr is pointer to an int – asterisk * in body to dereference the pointer cin >> *ptr; – address as argument to the function getNum(&num); // pass address of num to getNum
  • 39. Pointers as Function Parameters void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } int num1 = 2, num2 = -3; swap(&num1, &num2);
  • 40. Passing pointers as arguments When a pointer is passed as an argument, it divulges an address to the called function, so the function can change the value stored at that address: void passPointer(int* iPtr){ *iPtr += 2; // note *iPtr on left! } ... int i = 3; int* iPtr = &i; passPointer(iPtr); cout << "i = " << i << endl; // prints i = 5 passPointer(&i); // equivalent to above cout << "i = " << i << endl; // prints i = 7 End result same as pass-by-reference, syntax different. (Usually pass by reference is the preferred technique.) Glen Cowan RHUL Physics Computing and Statistical Data Analysis
  • 41. Pointers vs. reference variables A reference variable behaves like an alias for a regular variable. To declare, place & after the type: void passReference(int& i){ i += 2; } ... int i = 3; int& j = i; // j is a reference variable j = 7; cout << "i = " << i << endl; // prints i = 7 passReference(j); cout << "i = " << i << endl; // prints i = 9 Passing a reference variable to a function is the same as passing a normal variable by reference. Glen Cowan RHUL Physics Computing and Statistical Data Analysis
  • 42. What to do with pointers You can do lots of things with pointers in C++, many of which result in confusing code and hard-to-find bugs. One of the main differences between Java and C++: Java doesn’t have pointer variables (generally seen as a Good Thing). To learn about “pointer arithmetic” and other dangerous activities, consult most C++ books; we will not go into it here. The main usefulness of pointers for us is that they will allow us to allocate memory (create variables) dynamically, i.e., at run time, rather than at compile time. Glen Cowan RHUL Physics Computing and Statistical Data Analysis

Editor's Notes

  1. The dynamic memory allocation allows program to adjust its use of memory depending on the input.
  2. Much like a java reference (but more explicit) A pointer is a variable that contains the address of an object in memory. Line 1 – x is an integer, give it value 10 Line 3 – p gets the address of x
  3. Just like java. But you have to think about pointers.
  4. No garbage collection.