# Pointer Part1 by aaz104

VIEWS: 2 PAGES: 5

• pg 1
```									                                                                                                                                                3/25/2011

POINTERS
   Pointers are special variables that allow us to access
locations/address in memory in an indirect way.
    A pointer variable is a variable whose value is an address.
W10L18                                                     Some people use the terms pointer and address interchangeably

   Every byte in the computer’s memory has an address.

   The numbers start at 0 and go up from there—1, 2, 3, and
so on.

   If you have 1MB of memory, the highest address is
Department of Computer Science and                          1,048,575.
Information Technology, University of Gujrat

 Pointers     allow us to manipulate data through its
POINTERS
 This makes them very useful in several situations that we       Example:
will encounter
 pass by reference
 dynamic memory allocation
 This also makes them very dangerous because they allow        address variable name, value
us to access any part of memory
 InitializingPointers                                                   100:      px                 104         px is a pointer variable that
 A pointer variable is initialized by assigning an                                                               contains the address of an integer
address to it.                                                         104:      x                  -10         variable, x.
 We can access the address of a variable by
using the & operator                                                   108:                                     The value of px is address 104
 int *pnum, number; /* number is an int, pnum is an
The value of x is integer -10
We say that px points to x
Because x is an int, we say that the base type of px is int
 pnum     = &number; /* pnum now points to number */

POINTER        TO VOID
INITIALIZING POINTERS
    The address that you put in a pointer must be the            char *pletter, *pgrade;
same type as the pointer.                                     char grades[4] = {'A', 'B', 'C', 'D'};
char ch;

   int* ptrint = &flovar; //ERROR: can’t assign float* to int*   pletter = &ch;         /* now, pletter points to variable ch */
pletter = pgrade;     /* now, pletter points to the beginning of grades */

   There is a sort of general-purpose pointer that can           grades = pletter;   /*ILLEGAL! The address of an array is constant!
point to any data type. This is called a pointer to void.                              You cannot change its value */
pletter = 100; /* ILLEGAL! 100 is an integer, pletter's value should be an
   void* ptr; //ptr can point to any data type                   pletter = &pgrade /* ILLEGAL! pletter should be the address of a char,
a char). The types do not match. */

1
3/25/2011

THE ADDRESS-OF OPERATOR &                                                   POINTERS AND ARRAYS

       Find the address occupied by a variable by using the                    Array elements can be accessed using pointer
notation as well as array notation.
       #include <iostream>
       using namespace std;                                                 #include <iostream>
       int main()                                                           using namespace std;
       {
 int main()
       int var1 = 11;     //define and initialize
       int var2 = 22;     //three variables                                {                                          //array
       int var3 = 33;                                                       int intarray[5] = { 31, 54, 77, 52, 93 };
       cout << &var1 << endl //print the addresses                          for(int j=0; j<5; j++)           //for each element,
       << &var2 << endl //of these variables
 cout << *(intarray+j) << endl;       //print value
       << &var3 << endl;
       return 0;                                                            return 0;
       }                                                                   }

PASSING SIMPLE VARIABLES
POINTERS AND FUNCTIONS
       #include <iostream>
       using namespace std;
       int main()                                                                We have noticed that when passing an array to a
       {                                                                          function, we can modify the contents of the array
       void centimize(double&); //prototype                                       inside the function and the modifications survive
       double var = 10.0;               //var has value of 10 inches              when we return from the function.
       cout << “var = ” << var << “ inches” << endl;                             This is due to the fact that when we pass an array,
       centimize(var);                //change var to centimeters                 we actually pass the address where the array
       cout << “var = ” << var << “ centimeters” << endl;                         begins.
       return 0;                                                                 BIG IDEA: By passing the address of a variable, we
       }                                                                          are able to refer back to the variable in the calling
       //--------------------------------------------------------------           function.
       void centimize(double& v)                                                 In a way, this allows us to use the parameters for
       {                                                                          both input and output.
       v *= 2.54;                  //v is the same as var
       }

FUNCTION CALLS                                                              FUNCTION CALLS

   Actual parameters =                                                  At the start of a function call,
The values used during function calling                               The actual parameters are copied into
(a.k.a. arguments)                                                     the formal parameters (an assignment)
   Formal parameters =
The function’s local variables in the argument list
(these vars. are declared in the function prototype).

actual parameters                                       formal parameters   actual parameters                          formal parameters
int main () {                                                            int main () {
return 0;                                  return (x+y);                return 0;                          return (x+y);
}                                                               }
}                                                                        }

2
3/25/2011

FUNCTION CALLS                                                                   PASS BY VALUE / PASS BY REFERENCE

Recall functions and arrays:                                                      Parameter i copies a VALUE to use in function
The actual parameter is an array name; it holds address of 1st element             ‘pass by value’
in array                                                                        Parameter x copies a value that happens to be an ADDRESS
The formal parameter is a local array name; holds the same address                 ‘pass by reference’
(and keeps it fixed)

actual parameter                                 formal parameter                actual parameters                               formal parameters
int main () {                                                                    int main () {
double a[10];                                                                    double a[10];
void init(double x[], int i){                                                  void init(double x[], int i){
init(a,4);                                                                       init(a,4);
x[i] = 42.0;                                                                   x[i] = 42.0;
return 0;                                                                        return 0;
}                                                                              }
}                                                                                }

PASS BY REFERENCE                                                                POINTERS AND FUNCTIONS
 "Pass by reference" is a method of passing                                          Function arguments that are pointers
parameters into a function where instead of                                             Copy a value that happens to be an address to the formal
parameters
copying the value of a parameter, it passes the
   Dereferencing formal parameter lets us modify the value at the
address where that parameter is located.                                                 pointer  similar to ‘pass by reference’
 C does not really have "pass by reference". It
always copies the value. BUT, we can simulate                                  actual parameter
pass by reference by using a pointer variable
formal parameter
(whose value is always an address).                                        int main () {
void update(double *px) {
double num=1.234;
*px = 42.0;
update(&num);                          }
return 0;
} /* now num=42.0 */

POINTERS AND FUNCTIONS                                                           POINTERS AND FUNCTIONS
   Function arguments that are pointers
   Copy an address to the formal parameters,                            /* demonstration of pass-by-value */
   But changing formal parameter (the address) in the function          void increment (int number);
NEVER changes actual parameter!                                                                               1. function
int main () {                            increment is
int num = 5;                   called with
int main () {                                                                              increment(num);
printf("%d\n", num);
input 5
double num=1.234;                     void update(double *px) {
double *pnum;                                                                             return 0;                     3. on return from the function,
*px = 42.0;
pnum = &num;                                                                    }                                       the value of num is still 5
px++;
update(pnum);                         }                                         void increment (int number) {
return 0;                                                                                 number ++;              2. number is initialized to 5, then it is
} /* now num=42.0 */                         !
NO!                                   }
incremented by 1. The scope of number
/* pnum unchanged */                                                                                              is limited to the function. Its value is
lost on exit.

3
3/25/2011

POINTERS AND FUNCTIONS                                                                    POINTERS AND FUNCTIONS

/* demonstration of (simulated) pass-by-reference using pointers */                       /* using pointer arguments as output */

void increment (int *pnumber);                                                            void increment (int *number);
1. function increment is                                                        1. function increment is
int main () {                                          called with argument the           int main () {                                called with input the
int num = 5;                                 address of num                               int num;                           address of num. num is
increment(&num);                                                                          increment(&num);
printf("%d\n", num);                                                                      printf("%d\n", num);
not initialized at this time
return 0;                                  3. on return from the function,                return 0;                         3. on return from the function,
}                                                    the value of num has become 6        }                                           the value of num has become 10
void increment (int *pnumber) {                                                           void increment (int *pnumber) {
(*pnumber) ++;                       2. pnumber is initialized to the address             *pnumber=10;                 2. pnumber is initialized to the address
}                                                                                         }
of num. The code modifies the contents                                            of num. The code modifies the contents

PRINTING AN ARRAY

POINTERS AND ARRAYS                                                                           void print_array(int a[], int len) {
for (int i=0;i<len;i++)
 An array name is basically a const pointer.
cout << "[" << i << "] = "
 You can use the [] operator with a pointer:
<< a[i] << endl;
}
int      *x;
int      a[10];        x is “the address of a[2] ”
void print_array(int *a, int len) {
x =      &a[2];                                                                             for (int i=0;i<len;i++)
for      (int i=0;i<3;i++)                                                                      cout << "[" << i << "] = "
x[i]++;                                                                                           << *a++ << endl;
}
x[i] is the same as a[i+2]

21                                                                                      22

PASSING ARRAYS
   Arrays passed as arguments to functions, and their elements being accessed by
the function.                                                                         POINTERS AND ARRAYS
   #include <iostream>
   using namespace std;
   The concept of array is very similar to the concept of pointer. The
   const int MAX = 5;                  //number of array elements
identifier of an array actually a pointer that holds the address of
   int main()
the first element of the array.
   {                                                                                        Therefore if you have two declarations as follows:
   void centimize(double*); //prototype                                                          “int a[10];” “int* p;” then the assignment “p = a;” is perfectly valid
   double varray[MAX] = { 10.0, 43.1, 95.9, 59.7, 87.3 };                                        Also “*(a+4)” and “a[4]” are equivalent as are “*(p+4)” and “p[4]” .
   centimize(varray);               //change elements of varray to cm
   The only difference between the two is that we can change the value of
   for(int j=0; j<MAX; j++) //display new array values                                            “p” to any integer variable address whereas “a” will always point to
   cout << “varray[” << j << “]=”                                                                 the integer array of length 10 defined.
   << varray[j] << “ centimeters” << endl;
   return 0;
   }
   //--------------------------------------------------------------
   void centimize(double* ptrd)
   {
   for(int j=0; j<MAX; j++)
   *ptrd++ *= 2.54;             //ptrd points to elements of varray
   }

4
3/25/2011

CHARACTER POINTERS, ARRAYS                                              AND      STRINGS
   What is a String?                                                                      EXAMPLES
   A string is a character array that is ‘\0’ terminated.
   E.g. “Hello”                                                                          char* a = “Hello”;
   What is a Character array?                                                                     a -> gives address of ‘H’
   It is an array of characters, not necessarily ‘\0’ terminated                             *a -> gives ‘H’
   E.g. char test[4] = {‘a’, ‘b’, ‘c’, ‘d’}; <this char array is not zero                    a[0] -> gives ‘H’
terminated>
   a++ -> gives address of ‘e’
   What is a character pointer?                                                                  *a++ -> gives ‘e’
   It is a pointer to the address of a character variable.                                   a = &b; where b is another char variable is perfectly LEGAL.
   E.g. char* a; <this pointer is not initialized>                                            However “char a[100];” “a =&b;” where b is another char variable is
   How do we initialize a Character pointer?                                                      ILLEGAL.
 Initialize it to NULL. char* a = NULL;
 Let it point to a character array.
 char* a; char b[100]; a = b;

 Initialize to a character string.
 char* a = “Hello”; a pointer to the memory location where ‘H’ is
stored. Here “a” can be viewed as a character array of size 6,
the only difference being that a can be reassigned another
memory location.

5

```
To top