Title: Pointers
1Pointers
2What is a Pointer?
- A pointer is a type of variable that holds a
memory address. - In our compiler, memory addresses are 32 bits (4
bytes). - Anything can be at the address stored in a
pointer, e.g. char, short, int, a user defined
class, a string, an array, a function, etc.
3Using Pointers and Addresses
- Declare a pointer using the indirection
operator - Find an address using the address of operator
int MyVar 5 // an integer int pMyVar // a
pointer to an integer
cout ltlt MyVar ltlt MyVar cout ltlt address of
MyVar ltlt MyVar pMyVar MyVar
4The Value at the Address
- We retrieve the value of the data at the address
in a pointer using the indirection operator
int MyVar 5 int pMyVar MyVar cout ltlt
value of MyVar ltlt MyVar cout ltlt value
at pMyVar ltlt pMyVar cout ltlt address of
MyVar ltlt MyVar cout ltlt address in pMyVar
ltlt pMyVar
5Writing to the Address
- You can write to the address that the pointer
points to
int MyVar 5 int pMyVar MyVar pMyVar
10 // MyVar is set to 10
6Pointer Initialization
- Pointers should be initialized to an object, or
to null (0)
int MyVar 5 int pMyVar MyVar int
pOther 0 pOther NULL
7new and The "Free Store"
- You allocate memory on the free store in C by
using the new keyword. - new is followed by the type of the object that
you want to allocate. - The return value from new is a memory address, it
must be assigned to a pointer. - If new cannot allocate memory, it returns the
null pointer (0).
8delete and The "Free Store"
- When you finish with allocated memory, you must
free it by calling delete.
int pNewVar pNewVar new int if (pNewVar !
NULL) pNewVar 5 cout ltlt "pNewVar " ltlt
pNewVar ltlt endl delete pNewVar pNewVar
NULL
9The points-to operator -gt
- To access data members and functions of an object
through a pointer, we may use the shorthand -gt
Cat Frisky Cat pFrisky Frisky Frisky.SetAg
e(5) cout ltlt "Frisky's age " ltlt
Frisky.GetAge() (pFrisky).SetAge(6) cout ltlt
"Frisky's age " ltlt (pFrisky).GetAge() pFrisky-gt
SetAge(7) cout ltlt "Frisky's age " ltlt
pFrisky-gtGetAge()
10const Pointers, andPointers to const
- You can declare const pointers, which cant be
reassigned to point to other objects - You can declare pointers to const objects, which
cant be used to change the objects to which they
point
int iOne, iTwo, MyVar int const pTwo
iOne pTwo iTwo // cant reassign const
pointer const int pThree MyVar pThree 5
// cant change const variable MyVar 5 //
not an error