SlideShare a Scribd company logo
1 of 50
Download to read offline
FUNDAMENTALS OF
C++ PROGRAMMING
6.0 POINTER (PENUDING)
6.1 Understand the concept of pointer
Learning Outcome
   At the end of the class, student should be able
    to:
       Define pointer and explain its function
       Declare pointer
       Explain new and delete operators
What is pointer?
   Pointer is the memory address of a variable.
   Pointer is a variables that are used to store the
    addresses of other variables.
What is pointer?

               Memory Blocks




 0x8f8dfff12     0x8f8dfff13    0x8f8dfff14



          Address of Memory Blocks
Declaring Pointer

   Syntax:
       data_type   *pointer_name;

Example
    double *p;
The * and & operators
   * operator
     Reference/dereference operator

     Produce the variable to which it point

     Refer to “value pointed by”

     Pointers are said to "point to"



   Example of usage:
     double *p; // declare pointer to double variable

     void func(int *p) // declare p to be a pointer value
      parameter
The * and & operators
   & operator
     Address-of operator
     Produce address of variable
     Example:

      double *p, v;
      p = &v; // p point to address of v
Pointer Operator

           int *my_pointer;
           int my_variable;
           my_pointer = &my_variable;


                    my_pointer =
                    &my_variable

   Pointer                              Memory location
   variables           Address
                       operator
How it will look like?
#include<iostream>
using namespace std;
void main()
{
  int i;
  int *j;
  j = &i; //pointer to i
  i=4;

    cout<<"i = " <<i<<endl;
    cout<<"j = " <<j<<endl;
}
j = &i; //pointer to address i
    i=4;




i                  4

j                      0012FF60
What is the output???
 int i;
 int *j;
 j = &i; //pointer to i
 i=4;

 cout<<"i = " <<i<<endl;
 cout<<"j = " <<*j<<endl;
j = &i; //pointer to address i
i=4;


 i                 4

 j                     0012FF60

     cout<<"j = " <<*j

 j                       4
How it will look like?
#include<iostream>                            Output:
using namespace std;
void main()
                                           v1=42
{
   int *p1, v1;                            p1=42

    v1 = 0;                                 Why?
    p1 = &v1; //pointer to v1              - As long as p1
    *p1 = 42; //value pointed by p1 = 42     contains address to
                                             v1, then both refer
    cout<<"v1="<<v1<<endl;                   to the same
    cout<<"p1="<<*p1<<endl;                  variable
}
v1 = 0;

v1   0


 p1 = &v1;

                       &v
p1
                       1

 *p1 = 42; //value pointed by p1 = 42

     p1                     42


     v1                     42
See difference?
                          p1 = p2;

p1            8    p1                8

p2            9    p2                9


     BEFORE                AFTER
                        *p1 = *p2;

p1            8    p1                9


p2            9    p2                9
Pointer Arithmetic
   Pointer can only used two arithmetic operation
    addition and subtraction.

    int a, int *p;      W hat happen is:
    p=&a;                pointer move over bytes
    p=p+2;               not adding 2 to value of a
                         it point to the last 2 x int of the integer
                          a


Position of pointer p                     Position of pointer p after
  before operation                          p+2 operation
Pointer Arithmetic
  Example:                           its equivalent to:
#include<iostream>
using namespace std;                  #include<iostream>
void main()                           using namespace std;
{                                     void main()
   int arraysize=4;                   {
   int d []={1,2,3,4};                   int arraysize=4;
   for (int i = 0; i < arraysize; +      int d []={1,2,3,4};
   +i)                                   for (int i = 0; i < arraysize; ++i)
         cout << *(d + i) << " ";        cout << d[i] << " ";
}                                     }
Pointer & character string
   Use standard function strcmp() uses two pointers to compare
    two strings:

    strcmp (char *s1, char *s2)
    {
       while (*s1)
         if (*s1 - *s2)
                return *s1 - *s2;   //if the string are not equal
         else
                { s1++;
                   s2++;
                }
         return 0;
    }
new and delete operator
   new operator creates new dynamic variable of
    specific type
   It also return a pointer that point to this new
    variable
   Eg:
     int *n;
     n = new int(17); // initialize *n to 17
How it will look like?
int *p1, *p2;
                    p1   ?

                    p2   ?
p1 = new int;
*p1 = 42;
                    p1

                    p2   ?




                    p1
                             42

                    p2   ?
p2 = p1;         p2 = new int;
                   p1            ?
 p1
            42
 p2                p2            53


*p2 = 53;        *p1 = 88;
 p1                p1            88
            53
 p2                p2            53
   delete operator eliminates dynamic variable
   It also returns memory that the dynamic
    variable occupied in freestore.
   Eg:
     delete p;
    // p will be undefined
   Good practice:
       Everytime you delete a pointer variable put it to
        NULL to ensure it does not become dangling
        pointer!
#include<iostream>
using namespace std;
void main()
{
int *p1;
p1 = new int;
*p1 = 10;
    cout << "*p1 t = "<< *p1 << endl;
delete p1;
cout << "*p1 t = "<< *p1 << endl;
}
In Class Exercise 1
   What is the output?
                                     p1 = p2;
int *p1, *p2;
                                     cout << *p1 << "t"<< *p2 << endl;
p1 = new int;
                                     *p1 = 30;
p2 = new int;
                                     cout << *p1 << "t"<< *p2 << endl;
                                     *p1 = *p2;
*p1 = 10;
                                     cout << *p1 << "t"<< *p2 << endl;
*p2 = 20;
cout << *p1 << "t"<< *p2 << endl;
How it will look like?
int *p1, *p2;
                    p1   ?

                    p2   ?
p1 = new int;
p2 = new int;
                    p1

                    p2

*p1 = 10;
 *p2 = 20;          p1       10

                    p2       20
p1 = p2;
             p1    10

             p2    20




*p1 = 30;    p1   10

             p2   30



*p1 = *p2;   p1   30

             p2   30
In Class Exercise 2
   What is the different between the following
    variable?
    int *intPtr1, intPtr2;

   Write a declaration for a pointer variable
    named my_new_ptr that points to dynamic
    variable of type double.
6.2 Illustrate the relationship between
    pointer and array
Learning Outcome
   At the end of the class, student should be able
    to:
       Identify relationship between pointer and array
       Write program using pointer and array
Pointer & Array
   Array is a collection of similar type of data
   Variable in an array can store memory address
    instead of variable value
   Dynamic array is an array whose size is
    determined during run-time.
   It is created using new operator.
   Eg:
    double *new_array; //point to 1st index in the
    array
    new_array = new double[10] //to allocate
Pointer in Array: Example 1
#include<iostream>
using namespace std;
void main()
{
  int d []={1,2,3,4};
  int *p1;
  p1=d;
  for (int i = 0; i < 4; ++i)
        cout << *(p1 + i) << " ";
}
Pointer in Array: Example 2
#include <iostream>
using namespace std;
void main()
{
   int array_size;
   cout << “Enter array size: “;
   cin >> array_size;
   int* my_dyn_array = new int [array_size];

    cout << “Enter ” << array_size << “ number ” << endl;
    for (int i = 0; i < array_size; ++i)
           cin >> my_dyn_array[i];
}
Pointer and Array
   An array declared without specifying its size
    can be assume as a pointer to the address of
    the first element in the array.
   Eg:
    int a[] = {2, 4, 6, 8, 10};
   To iterate to the next element, add operation is
    used.
Pointer and Array: Example 1
#include <iostream>
using namespace std;
int main()
{
    char susun[] = "Selamat belajar";
    char * pt_str;
    pt_str = susun; / point to first element
                    /
    cout << "Turutan sblm perubahan " << susun;
    cout << "
             nSebelum perubahan, kandungan susun[5] : " <<susun[5];
    * (pt_str+5) = 'C'; /change the 6th element
                        /
    cout << "
             nSelepas perubahan, kandungan susun[5] : " <<susun[5];
    cout << "
             nTurutan slps perubahan" << susun;
    return 0;
}
Pointer and Array: Example 2
#include <iostream>
using namespace std;
int main()
{
    int senarai[] = {1,2,3,4,5};
    int * point;
    point=senarai; / point to first element
                   /
    cout << "
             nTurutan sblm perubahan " << senarai[0] << " " << senarai[1];
    cout << " " << senarai[2] << " " << senarai[3] << " " << senarai[4];
    cout << "
             nSebelum perubahan, kandungan senarai[2] : " <<senarai[2];
    * (point+2)= 7; / change the 3rd element
                    /
    cout << "
             nSelepas perubahan, kandungan senarai[2] : " <<senarai[2];
    cout << "
             nTurutan slps perubahan " << senarai[0] << " " << senarai[1];
    cout << " " << senarai[2] << " " << senarai[3] << " " << senarai[4];
    cout << endl;
    return 0;
}
In Class Exercise 3
   Write a declaration for pointer variable named
    char_ptr that will be used to point to a dynamic
    array of type char.
   What is the output for the following code?
      int c[3] = {2, 3, 4};
      int arraysize = 3, * p;
      p = c;
      for (int i = 0; i < arraysize; ++i)
         cout << c[i] << “ “;
      for (i = 0; i < arraysize; ++i)
         cout << * (p + i) << “ “;
   Declaration
    char * char_ptr; //point to 1st index in the array
     char_ptr = new char[6];

   What is the output for the following code?
6.3 Illustrate the relationship between
    pointer and function
Learning Outcome
   At the end of the class, student should be able
    to:
       Identify relationship between pointer and function
       Use pointer as function argument
       Write program using pointer and function
Pointer & Functions
   2 types of function calls:
       Call by value
       Call by reference

   Pointer can be used as parameters in both
    function
Pointers & Function
#include <iostream>
using namespace std;                         void Change (int *a, int *b, int *c)
                                                {
void Change (int *, int *, int *);              *a = 100;
                                                *b = 200;
                                                *c = 300;
void main()                                     }
    {
    int x=50, y=60, z=70;
    cout << "nx = " << x << "ny = " << y                            received address
        << "nz = " << z << "nn";
    Change (&x, &y, &z);
    cout << "nx = " << x << "ny = " << y
        << "nz = " << z << "nn";          change value in
    }                                        variable that is point
                                             by a,b,c
How it will look like?
Change(&x, &y, &z);
void Change(int *a, int *b, int *c)
 {                                 &x
                            50
 *a = 100;              x (100)         1001
                                   *a
 *b = 200;                 1001         *a
                                   &y
 *c = 300;                  60
                        y (200)         1002
 }                         1002
                                   *b
                                        *b

                            70     &z
                        z (300)         1003
                                   *c
                           1003         *c
Pointers & Function
#include <iostream>                         void Change (int &a, int &b, int &c)
using namespace std;                           {
                                               a = 100;
                                               b = 200;
void Change (int &, int &, int &);
                                               c = 300;
                                               }
void main()                                                          received address
   {
   int x=50, y=60, z=70;
   cout << "nx = " << x << "ny = " << y
       << "nz = " << z << "nn";               change value refered by
   Change (x, y, z);                             a,b,c
   cout << "nx = " << x << "ny = " << y
       << "nz = " << z << "nn";
   }
Summary
   Pointer is a memory address
   Pointer variable provides way to indirectly
    name variable by naming the address of
    variable in memory
    new and delete operator can be use to
    allocate and free the memory after pointer is
    used
   Dynamic array is array whose sized is
    determined during runtime
   Function can have pointer variable as its
    parameter variables.

More Related Content

What's hot (20)

Pointers
PointersPointers
Pointers
 
Ch7 C++
Ch7 C++Ch7 C++
Ch7 C++
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
This pointer
This pointerThis pointer
This pointer
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
CBSE Class XI Programming in C++
CBSE Class XI Programming in C++CBSE Class XI Programming in C++
CBSE Class XI Programming in C++
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Array notes
Array notesArray notes
Array notes
 
functions
functionsfunctions
functions
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 

Viewers also liked

Viewers also liked (6)

Fp201 unit1 1
Fp201 unit1 1Fp201 unit1 1
Fp201 unit1 1
 
FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit 3
Unit 3Unit 3
Unit 3
 
Unit 2
Unit 2Unit 2
Unit 2
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 

Similar to Here are the answers:1. char *char_ptr;2. 2 3 4

Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxajajkhan16
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehmanNauman Rehman
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programmingClaus Wu
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfsudhakargeruganti
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingMeghaj Mallick
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxhappycocoman
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Languagemadan reddy
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanMohammadSalman129
 

Similar to Here are the answers:1. char *char_ptr;2. 2 3 4 (20)

Pointer
PointerPointer
Pointer
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
pointers
pointerspointers
pointers
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 
C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
 
Pointers
PointersPointers
Pointers
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptx
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 

More from rohassanie

Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012rohassanie
 
FP 202 - Chapter 5
FP 202 - Chapter 5FP 202 - Chapter 5
FP 202 - Chapter 5rohassanie
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2rohassanie
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1rohassanie
 
FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3rohassanie
 
Chapter 2 (Part 2)
Chapter 2 (Part 2) Chapter 2 (Part 2)
Chapter 2 (Part 2) rohassanie
 
Labsheet 7 FP 201
Labsheet 7 FP 201Labsheet 7 FP 201
Labsheet 7 FP 201rohassanie
 
Labsheet 6 - FP 201
Labsheet 6 - FP 201Labsheet 6 - FP 201
Labsheet 6 - FP 201rohassanie
 
Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012rohassanie
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1rohassanie
 
Labsheet2 stud
Labsheet2 studLabsheet2 stud
Labsheet2 studrohassanie
 
Labsheet1 stud
Labsheet1 studLabsheet1 stud
Labsheet1 studrohassanie
 
Chapter 1 part 3
Chapter 1 part 3Chapter 1 part 3
Chapter 1 part 3rohassanie
 
Chapter 1 part 2
Chapter 1 part 2Chapter 1 part 2
Chapter 1 part 2rohassanie
 
Chapter 1 part 1
Chapter 1 part 1Chapter 1 part 1
Chapter 1 part 1rohassanie
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++rohassanie
 

More from rohassanie (20)

Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012
 
FP 202 - Chapter 5
FP 202 - Chapter 5FP 202 - Chapter 5
FP 202 - Chapter 5
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1
 
FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3
 
Lab ex 1
Lab ex 1Lab ex 1
Lab ex 1
 
Chapter 2 (Part 2)
Chapter 2 (Part 2) Chapter 2 (Part 2)
Chapter 2 (Part 2)
 
Labsheet 7 FP 201
Labsheet 7 FP 201Labsheet 7 FP 201
Labsheet 7 FP 201
 
Labsheet 6 - FP 201
Labsheet 6 - FP 201Labsheet 6 - FP 201
Labsheet 6 - FP 201
 
Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012
 
Labsheet 5
Labsheet 5Labsheet 5
Labsheet 5
 
Labsheet 4
Labsheet 4Labsheet 4
Labsheet 4
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1
 
Labsheet_3
Labsheet_3Labsheet_3
Labsheet_3
 
Labsheet2 stud
Labsheet2 studLabsheet2 stud
Labsheet2 stud
 
Labsheet1 stud
Labsheet1 studLabsheet1 stud
Labsheet1 stud
 
Chapter 1 part 3
Chapter 1 part 3Chapter 1 part 3
Chapter 1 part 3
 
Chapter 1 part 2
Chapter 1 part 2Chapter 1 part 2
Chapter 1 part 2
 
Chapter 1 part 1
Chapter 1 part 1Chapter 1 part 1
Chapter 1 part 1
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 

Here are the answers:1. char *char_ptr;2. 2 3 4

  • 2. 6.1 Understand the concept of pointer
  • 3. Learning Outcome  At the end of the class, student should be able to:  Define pointer and explain its function  Declare pointer  Explain new and delete operators
  • 4. What is pointer?  Pointer is the memory address of a variable.  Pointer is a variables that are used to store the addresses of other variables.
  • 5. What is pointer? Memory Blocks 0x8f8dfff12 0x8f8dfff13 0x8f8dfff14 Address of Memory Blocks
  • 6. Declaring Pointer  Syntax: data_type *pointer_name; Example double *p;
  • 7. The * and & operators  * operator  Reference/dereference operator  Produce the variable to which it point  Refer to “value pointed by”  Pointers are said to "point to"  Example of usage:  double *p; // declare pointer to double variable  void func(int *p) // declare p to be a pointer value parameter
  • 8. The * and & operators  & operator  Address-of operator  Produce address of variable  Example: double *p, v; p = &v; // p point to address of v
  • 9. Pointer Operator int *my_pointer; int my_variable; my_pointer = &my_variable; my_pointer = &my_variable Pointer Memory location variables Address operator
  • 10. How it will look like? #include<iostream> using namespace std; void main() { int i; int *j; j = &i; //pointer to i i=4; cout<<"i = " <<i<<endl; cout<<"j = " <<j<<endl; }
  • 11. j = &i; //pointer to address i i=4; i 4 j 0012FF60
  • 12. What is the output??? int i; int *j; j = &i; //pointer to i i=4; cout<<"i = " <<i<<endl; cout<<"j = " <<*j<<endl;
  • 13. j = &i; //pointer to address i i=4; i 4 j 0012FF60 cout<<"j = " <<*j j 4
  • 14. How it will look like? #include<iostream>  Output: using namespace std; void main() v1=42 { int *p1, v1; p1=42 v1 = 0;  Why? p1 = &v1; //pointer to v1 - As long as p1 *p1 = 42; //value pointed by p1 = 42 contains address to v1, then both refer cout<<"v1="<<v1<<endl; to the same cout<<"p1="<<*p1<<endl; variable }
  • 15. v1 = 0; v1 0 p1 = &v1; &v p1 1 *p1 = 42; //value pointed by p1 = 42 p1 42 v1 42
  • 16. See difference? p1 = p2; p1 8 p1 8 p2 9 p2 9 BEFORE AFTER *p1 = *p2; p1 8 p1 9 p2 9 p2 9
  • 17. Pointer Arithmetic  Pointer can only used two arithmetic operation addition and subtraction. int a, int *p; W hat happen is: p=&a;  pointer move over bytes p=p+2;  not adding 2 to value of a  it point to the last 2 x int of the integer a Position of pointer p Position of pointer p after before operation p+2 operation
  • 18. Pointer Arithmetic  Example: its equivalent to: #include<iostream> using namespace std; #include<iostream> void main() using namespace std; { void main() int arraysize=4; { int d []={1,2,3,4}; int arraysize=4; for (int i = 0; i < arraysize; + int d []={1,2,3,4}; +i) for (int i = 0; i < arraysize; ++i) cout << *(d + i) << " "; cout << d[i] << " "; } }
  • 19. Pointer & character string  Use standard function strcmp() uses two pointers to compare two strings: strcmp (char *s1, char *s2) { while (*s1) if (*s1 - *s2) return *s1 - *s2; //if the string are not equal else { s1++; s2++; } return 0; }
  • 20. new and delete operator  new operator creates new dynamic variable of specific type  It also return a pointer that point to this new variable  Eg: int *n; n = new int(17); // initialize *n to 17
  • 21. How it will look like? int *p1, *p2; p1 ? p2 ? p1 = new int; *p1 = 42; p1 p2 ? p1 42 p2 ?
  • 22. p2 = p1; p2 = new int; p1 ? p1 42 p2 p2 53 *p2 = 53; *p1 = 88; p1 p1 88 53 p2 p2 53
  • 23. delete operator eliminates dynamic variable  It also returns memory that the dynamic variable occupied in freestore.  Eg: delete p; // p will be undefined  Good practice:  Everytime you delete a pointer variable put it to NULL to ensure it does not become dangling pointer!
  • 24. #include<iostream> using namespace std; void main() { int *p1; p1 = new int; *p1 = 10; cout << "*p1 t = "<< *p1 << endl; delete p1; cout << "*p1 t = "<< *p1 << endl; }
  • 25. In Class Exercise 1  What is the output? p1 = p2; int *p1, *p2; cout << *p1 << "t"<< *p2 << endl; p1 = new int; *p1 = 30; p2 = new int; cout << *p1 << "t"<< *p2 << endl; *p1 = *p2; *p1 = 10; cout << *p1 << "t"<< *p2 << endl; *p2 = 20; cout << *p1 << "t"<< *p2 << endl;
  • 26.
  • 27. How it will look like? int *p1, *p2; p1 ? p2 ? p1 = new int; p2 = new int; p1 p2 *p1 = 10; *p2 = 20; p1 10 p2 20
  • 28. p1 = p2; p1 10 p2 20 *p1 = 30; p1 10 p2 30 *p1 = *p2; p1 30 p2 30
  • 29. In Class Exercise 2  What is the different between the following variable? int *intPtr1, intPtr2;  Write a declaration for a pointer variable named my_new_ptr that points to dynamic variable of type double.
  • 30. 6.2 Illustrate the relationship between pointer and array
  • 31. Learning Outcome  At the end of the class, student should be able to:  Identify relationship between pointer and array  Write program using pointer and array
  • 32. Pointer & Array  Array is a collection of similar type of data  Variable in an array can store memory address instead of variable value  Dynamic array is an array whose size is determined during run-time.  It is created using new operator.  Eg: double *new_array; //point to 1st index in the array new_array = new double[10] //to allocate
  • 33. Pointer in Array: Example 1 #include<iostream> using namespace std; void main() { int d []={1,2,3,4}; int *p1; p1=d; for (int i = 0; i < 4; ++i) cout << *(p1 + i) << " "; }
  • 34. Pointer in Array: Example 2 #include <iostream> using namespace std; void main() { int array_size; cout << “Enter array size: “; cin >> array_size; int* my_dyn_array = new int [array_size]; cout << “Enter ” << array_size << “ number ” << endl; for (int i = 0; i < array_size; ++i) cin >> my_dyn_array[i]; }
  • 35. Pointer and Array  An array declared without specifying its size can be assume as a pointer to the address of the first element in the array.  Eg: int a[] = {2, 4, 6, 8, 10};  To iterate to the next element, add operation is used.
  • 36. Pointer and Array: Example 1 #include <iostream> using namespace std; int main() { char susun[] = "Selamat belajar"; char * pt_str; pt_str = susun; / point to first element / cout << "Turutan sblm perubahan " << susun; cout << " nSebelum perubahan, kandungan susun[5] : " <<susun[5]; * (pt_str+5) = 'C'; /change the 6th element / cout << " nSelepas perubahan, kandungan susun[5] : " <<susun[5]; cout << " nTurutan slps perubahan" << susun; return 0; }
  • 37.
  • 38. Pointer and Array: Example 2 #include <iostream> using namespace std; int main() { int senarai[] = {1,2,3,4,5}; int * point; point=senarai; / point to first element / cout << " nTurutan sblm perubahan " << senarai[0] << " " << senarai[1]; cout << " " << senarai[2] << " " << senarai[3] << " " << senarai[4]; cout << " nSebelum perubahan, kandungan senarai[2] : " <<senarai[2]; * (point+2)= 7; / change the 3rd element / cout << " nSelepas perubahan, kandungan senarai[2] : " <<senarai[2]; cout << " nTurutan slps perubahan " << senarai[0] << " " << senarai[1]; cout << " " << senarai[2] << " " << senarai[3] << " " << senarai[4]; cout << endl; return 0; }
  • 39.
  • 40. In Class Exercise 3  Write a declaration for pointer variable named char_ptr that will be used to point to a dynamic array of type char.  What is the output for the following code? int c[3] = {2, 3, 4}; int arraysize = 3, * p; p = c; for (int i = 0; i < arraysize; ++i) cout << c[i] << “ “; for (i = 0; i < arraysize; ++i) cout << * (p + i) << “ “;
  • 41. Declaration char * char_ptr; //point to 1st index in the array char_ptr = new char[6];  What is the output for the following code?
  • 42. 6.3 Illustrate the relationship between pointer and function
  • 43. Learning Outcome  At the end of the class, student should be able to:  Identify relationship between pointer and function  Use pointer as function argument  Write program using pointer and function
  • 44. Pointer & Functions  2 types of function calls:  Call by value  Call by reference  Pointer can be used as parameters in both function
  • 45. Pointers & Function #include <iostream> using namespace std; void Change (int *a, int *b, int *c) { void Change (int *, int *, int *); *a = 100; *b = 200; *c = 300; void main() } { int x=50, y=60, z=70; cout << "nx = " << x << "ny = " << y received address << "nz = " << z << "nn"; Change (&x, &y, &z); cout << "nx = " << x << "ny = " << y << "nz = " << z << "nn"; change value in } variable that is point by a,b,c
  • 46.
  • 47. How it will look like? Change(&x, &y, &z); void Change(int *a, int *b, int *c) { &x 50 *a = 100; x (100) 1001 *a *b = 200; 1001 *a &y *c = 300; 60 y (200) 1002 } 1002 *b *b 70 &z z (300) 1003 *c 1003 *c
  • 48. Pointers & Function #include <iostream> void Change (int &a, int &b, int &c) using namespace std; { a = 100; b = 200; void Change (int &, int &, int &); c = 300; } void main() received address { int x=50, y=60, z=70; cout << "nx = " << x << "ny = " << y << "nz = " << z << "nn"; change value refered by Change (x, y, z); a,b,c cout << "nx = " << x << "ny = " << y << "nz = " << z << "nn"; }
  • 49.
  • 50. Summary  Pointer is a memory address  Pointer variable provides way to indirectly name variable by naming the address of variable in memory  new and delete operator can be use to allocate and free the memory after pointer is used  Dynamic array is array whose sized is determined during runtime  Function can have pointer variable as its parameter variables.