SlideShare a Scribd company logo
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

PPTX
Pointers in C
PPTX
Pointers in C
PDF
Lecturer23 pointersin c.ppt
PPT
detailed information about Pointers in c language
PPTX
Dynamic Memory Allocation in C
PPTX
Used of Pointer in C++ Programming
PPT
C pointers
Pointers in C
Pointers in C
Lecturer23 pointersin c.ppt
detailed information about Pointers in c language
Dynamic Memory Allocation in C
Used of Pointer in C++ Programming
C pointers

What's hot (20)

PPTX
Learning C++ - Pointers in c++ 2
ODP
Pointers in c++ by minal
PDF
Pointer in c++ part1
PPTX
C programming - Pointers
PDF
Pointers_c
PPTX
Pointers in C/C++ Programming
PDF
Types of pointer in C
PPT
Pointers+(2)
PDF
Pointers & References in C++
PPT
Pointers in C
PDF
C++ Chapter IV
PDF
C++ Chapter III
PPTX
Pointers in c++
PPT
PPTX
Pointer in c
PPT
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
PDF
See through C
PPT
Advanced pointers
PPT
Pointers in c
PPTX
Pointers in c++
Learning C++ - Pointers in c++ 2
Pointers in c++ by minal
Pointer in c++ part1
C programming - Pointers
Pointers_c
Pointers in C/C++ Programming
Types of pointer in C
Pointers+(2)
Pointers & References in C++
Pointers in C
C++ Chapter IV
C++ Chapter III
Pointers in c++
Pointer in c
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
See through C
Advanced pointers
Pointers in c
Pointers in c++
Ad

Similar to oop Lecture 17 (20)

PPT
Pointers
PDF
PDF
Pointers
PPTX
Object Oriented Programming using C++: Ch10 Pointers.pptx
PPT
Lec 40.41 - pointers
PPT
Lec 36 - pointers
PPTX
Pf cs102 programming-9 [pointers]
PPTX
Computer Programming Lecture numer 05 -- pointers,variablesb
PPT
Lec 37 - pointers
PPTX
L4_Pointer Arithmetic in C++.pptxhwhwjwjw
PPT
FP 201 - Unit 6
PPTX
PDF
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
PPTX
INTRODUCTION TO POINTER IN c++ AND POLYMORPHISM
PDF
Computer programming course(c++ pointer))
PPTX
C++ Pointer | Introduction to programming
PPT
C96e1 session3 c++
PDF
C Pointers
PDF
C++ computer language chapter 4 pointers.pdf
Pointers
Pointers
Object Oriented Programming using C++: Ch10 Pointers.pptx
Lec 40.41 - pointers
Lec 36 - pointers
Pf cs102 programming-9 [pointers]
Computer Programming Lecture numer 05 -- pointers,variablesb
Lec 37 - pointers
L4_Pointer Arithmetic in C++.pptxhwhwjwjw
FP 201 - Unit 6
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
INTRODUCTION TO POINTER IN c++ AND POLYMORPHISM
Computer programming course(c++ pointer))
C++ Pointer | Introduction to programming
C96e1 session3 c++
C Pointers
C++ computer language chapter 4 pointers.pdf
Ad

More from Anwar Ul Haq (12)

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

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation_ Review paper, used for researhc scholars
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
KodekX | Application Modernization Development
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
Encapsulation_ Review paper, used for researhc scholars
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
cuic standard and advanced reporting.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
KodekX | Application Modernization Development
Chapter 3 Spatial Domain Image Processing.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
The AUB Centre for AI in Media Proposal.docx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
MIND Revenue Release Quarter 2 2025 Press Release
Advanced methodologies resolving dimensionality complications for autism neur...
Digital-Transformation-Roadmap-for-Companies.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

  • #5: The dynamic memory allocation allows program to adjust its use of memory depending on the input.
  • #12: 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
  • #32: Just like java. But you have to think about pointers.
  • #33: No garbage collection.