Docstoc

pointer (PowerPoint)

Document Sample
pointer (PowerPoint) Powered By Docstoc
					Pointers: Part I
             Why pointers?
- low-level, but efficient manipulation of memory

- dynamic objects

   Objects whose memory is allocated during program
    execution. (Dynamic objects can survive after the function
    ends in which they were allocated).
   Dynamic objects allow flexible-sized arrays and
    lists
Computer Memory and Variables
   A variable is a symbolic name assigned to some memory
    storage
   The size of this storage depends on the type of the variable:
    one byte char, 4 bytes int
   The name of variable is in ‘symbol table’ by compiler: each
    symbol is associated with its type, location, scope …

   So, the compiler manages its location  good for
    programmers!
                                                         Symbol table
Memory address:      1020       1024                     a: int, 1024, …

           … …                  100       …
                            int a=100;
                          Pointers
  A pointer is a variable used for storing the
   address of a memory cell.
  We can use the pointer to reference this
   memory cell, so to ‘manipulate’ it!
                         Object whose value represents the location
                          (memory address) of another object


Memory address:    1020         1024                  10032

          … …                   100        …          1024       …
int a;
                  Integer a                               Pointer p
int* p;
    Define a pointer type variable
Each type of object (variable) has a pointer type, therefore
  a pointer variable of that type.


 TypeName* variablename;                              int* p;
                          equivalent

 TypeName *variablename;                              int *p;

Examples of (uninitialized) pointers
   int* ip;
   char* s;
   int *ip;            // ip is a pointer to an int
   char *s;              // s is a pointer to a char
Getting an address: address operator &
 int a=100;    “&a”  “the address of a”

Memory address: 1020    1024

         … …             100    … … …
                          a
        int a = 100;
        cout << a;      100
        Cout << &a;     1024
   Store the address in a pointer variable
   Memory address:     1020        1024                  10032

               …          88        100       …          1024        …
                                      a                     p
     int a = 100;
     int* p = &a;                                       Result is:
     cout << a << " " << &a <<endl;                     100 1024

              The value of pointer p is the address of variable a

     cout << p << " " << &p <<endl;                     1024 10032

              A pointer is also a variable, so it has its own memory address
p is pointing to a
         Dereferencing Operator *
  We can access to the value stored in the variable
   pointed to by preceding the pointer with the “star”
   operator (*),
Memory address:   1020    1024               10032

          …         88     100      …        1024        …
                             a                  p
int a = 100;
int* p = &a;
cout << a << endl;
cout << &a << endl;
cout << p << " " << *p << endl;
                                           *p       gives 100
cout << &p << endl;
An asterisk (‘*’) has two usages

   In a definition, an asterisk indicates that the
    object is a pointer.
     char* s; // s is of type pointer to char
     (char *s; is possible)
   In expressions, an asterisk before a pointer
    indicates the object the pointer pointed to,
    called dereferencing
     int i = 1, j;
     int* ptr;        // ptr is an int pointer
     ptr = &i;        // ptr points to i
     j = *ptr + 1;    // j is assigned 2
     cout << *ptr << j << endl; // display "12"
Summary on two operators * and &

    * has two usages:
          - pointer
          - dereferencing
    & has two usages:
          - getting address
          - reference (‘call by ref’, see later)
                Null Address

 0 is a pointer constant that represents
  the empty or null address
   Indicates that pointer is not pointing to storage of a
    valid object
   Cannot dereference a pointer whose value is null
     int* ptr;
     ptr = 0;
     cout << *ptr << endl; // invalid, ptr
                           // does not point to
                           // a valid int
                   Example
#include <iostream>
using namespace std;                  Result:
int main (){                          Value1 is 10
  int value1 = 5, value2 = 15;
                                      Value2 is 20
  int* p1;
  int* p2;
  p1 = &value1; // p1 = address of value1
  p2 = &value2; // p2 = address of value2
  *p1 = 10;     // value pointed to by p1=10
  *p2 = *p1;    // value pointed to by p2= value
                // pointed to by p1
  p1 = p2;      // p1 = p2 (pointer value copied)
  *p1 = 20;     // value pointed to by p1 = 20
  cout << "value1==" << value1 << "/ value2==" <<
  value2;
  return 0;
}
Another Pointer Example
int a = 3;
char s = ‘z’;
double d = 1.03;
int* pa = &a;
char* ps = &s;
double* pd = &d;
cout << sizeof(pa) << sizeof(*pa)
     << sizeof(&pa) << endl;
cout << sizeof(ps) << sizeof(*ps)
     << sizeof(&ps) << endl;
cout << sizeof(pd) << sizeof(*pd)
     << sizeof(&pd) << endl;
   Writing pointer type properly
            in C++ …         Recommended:
                                int* a;
                                         ?
                                               int* b;
int *a, *b;             int*    a, b;
a, b are both integer   a is integer pointer, b is
   pointers                just integer!


                typedef int MyInt;
                                                 int k;
                MyInt k;


      typedef int* IntPt;
      IntPt a, b;
      Traditional Pointer Usage
 void swap(char* ptr1, char* ptr2){
     char temp = *ptr1;
     *ptr1 = *ptr2;
     *ptr2 = temp;
 }
 int main() {
     char a = 'y';
     char b = 'n';
     swap(&a, &b);
     cout << a << b << endl;
     return 0;
 }
Use pass-by-value of pointers to ‘change’ variable values
C language does not have ‘call by reference’, only ‘call by value’!
                       Reference: X&

                                   void f(int& b) {};

 int& b a;                        int main() {
 b is an alternative name for a
                                     int a;
                                     f(a);
                                   }
      Pass by reference (better than
               ‘pointers’)
 void swap(char& y, char& z) {
     char temp = y;
     y = z;
     z = temp;
 }
 int main() {
     char a = 'y';
     char b = 'n';
     swap(a, b);
     cout << a << b << endl;
     return 0;
 }
y, z are ‘references’, only names, not like ptr1, ptr2 that are variables
            it is also possible (not
               recommended)…
 void swap(char &y, char &z) {
     char temp = y;
     y = z;
     z = temp;
 }
 int main() {
     char a = 'y';
     char b = 'n';
     swap(a, b);
     cout << a << b << endl;
     return 0;
 }
This is just an alternative way of writing ‘reference’.
Pointers and arrays
           Arrays are pointers!
The name of an array points only to the first element
  not the whole array.


                  1000

                  1004

                  1008

                  1012

                  1016
Array name is a pointer constant

  #include <iostream>
  Using namespace std;

  void main (){
        // Demonstrate array name is a pointer constant
        int a[5];
        cout << "Address of a[0]: " << &a[0] << endl
             << "Name as pointer: " << a << endl;
  }

  /* result:
  Address of a[0]: 0x0065FDE4
  Name as pointer: 0x0065FDE4
  */
 Dereference of an array name


              #include <iostream>
              Using namespace std;
              void main(){
a[0]   2        int a[5] = {2,4,6,8,22};            Result is:
a[1]   4        cout << *a << " "                   2
                     << a[0] << " "                 2
a[2]   6             << *(&a[0]);                   2
a[3]   8        ..."
a[4]   22     } //main


                This element is called a[0] or *a
Array name as pointer

To access an array, any pointer to the first element
  can be used instead of the name of the array.
                                 We could replace *p by *a
               #include <iostream>
               Using namespace std;
   a   p       void main(){
                 int a[5] = {2,4,6,8,22};
a[0]    2
                 int* p = a;
a[1]    4
                 int i = 0;
a[2]    6
                 cout << a[i] << " "                  2
a[3]    8
                      << *p;
a[4]   22
                 ...                              2
       a       }
       Multiple Array Pointers
Both a and p are pointers to the same array.
                                    #include <iostream>
                                    Using namespace std;
            A[0]                    void main(){
a[0]                    22            int a[5] = {2,4,6,8,22}
       2           p
                        44            int* p = &a[1];
a[1]   4
                                      cout << a[0] << " "
a[2]   6
            P[0]                           << p[-1];
a[3]   8                              cout << a[1] << " "
a[4]   22                                  << p[0];
                                      ...
                                    }
                 Pointer Arithmetic
Given a pointer p, p+n refers to the element that is
  offset from p by n positions.


            a             2         p - 1

         a + 1            4         p
         a + 2            6         p + 1
         a + 3            8         p + 2
         a + 4           22         p + 3
   Dereferencing Array Pointers

a[0]   or *(a + 0)           2        a
a[1]   or   *(a   +   1)     4        a   +   1
a[2]   or   *(a   +   2)     6        a   +   2
a[3]   or   *(a   +   3)     8        a   +   3
a[4]   or   *(a   +   4)     22       a   +   4



        *(a+n) is identical to a[n]
                                 Summary
 *   two usages:
        - pointer type definition: int a;
                                    int* p;
        - dereferencing: *p is an integer variable if
                                               p = &a;
& two usages:
        - getting address: p = &a;
        - reference: int& b a;
                       b is an alternative name for a
First application in passing parameters (‘swap’ example)

  int a=10;
  int b=100;
  int* p;                                  p = q;          ?
  int* q;
  p=&a;                                    *p = *q;        ?
  q=&b;
Two ways of manipulating an array

   A[n]: like a vector, an array
   *(a+n): like a ‘sequence’ or a ‘list’

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:2
posted:2/14/2012
language:
pages:28