Pointer and Dynamic Arrays
- Pointers are memory addresses used to indirectly access a variable
- The &is used to access the address
- int num =80;
- So, the address of the variable num is accessed as: &num
- A pointer is declared using an *
- int *p; // p is a pointer to an integer
- p = # // p is now a reference to num
Addresses and Pointers
& is used as an address operator
int i = 6;
p = &i; /*The address of i is given to p ( p points to i) */
The * operator is also used to access a location pointed to by an address
*p = 5; /*Location pointed to by p is changed to a 5 (as well as i)
A pointer is declared using the *
int *p; / *declares a pointer to an integer - no space is allocated */
An example
int i=5, *p;
cout << "hello" << I <, endl;
cout << p << &i ;
p = &i;
cout << " \n"<< p<< &i;
*p = 80;
cout << " \n"<< i<< *p;
CRASH
Pointers can be used to point to arrays - using either of the 2
following assignment statements:
int v[10], *vPtr, I;
vPtr = v;
vPtr = &v[0];
for (I = 0; I < 10; I++)
cout << "Element " << I << " is "
<< *(gptr + I) << endl;
Static Array Allocation
Declare an array of character pointers as:
char *string[5] = {"one", "two", "three", "four", "five"};
This produces five pointers. Where string[0] points to "one", and string[4] points to "five".
Dynamic Array Allocation
char *name;
name = new char[40];
Pointer Expressions and Arithmetic
Pointer arithmetic is permitted
vPtr has the value (i.e., address) of 3000
vPtr + 2 in conventional arithmetic would be 3002, but vPtr += 2;
produces 3008 -gt; (3002 + 2 * 4) assuming an integer is stored in 4 bytes
To access array element v[3]
*(vPtr + 3) / * Parentheses needed to override precedence */
Increments are scaled when used with pointers based on the size of what is being pointed to.
*ptr++ Use pointer then increment
*++ptr Increment pointer before using
Pointer Initialization
Initialize pointer when declared by:
int *ptr = &number;
Passing Addresses
Calling by value is the default; Use pointers to pass by reference
Use &var_name in call
Use *param_name in header
Use type * in prototype
Passing Arrays
The address of an array is the address of the 1st element of the array
Example
int findmax (int *, int)
findmax (nums, 10) nums has 10 elem
int findmax(int *vals, int size);
Multidimensional Arrays
In header and prototype, the size of the first dimension may be omitted.
Look at the
Power Point Slides
for chapter 9