Chapter Four: Pointers
Chapter Four: Pointers
Chapter Four: Pointers
Pointers
Pointer
• A pointer is a variable that holds the address of
something else.
• Syntax :
dataType *identifier;
e.g.
int *x;
x is a pointer to an integer.
• Addresses: garbage, something, nothing
– When created:
int * q;
q = 0; // now it points to nothing
q = NULL; // not portable, use 0 instead
Pointers to anything
x some int
int *x;
z some double
double *z;
int foo; 0
1
int *x; 2
foo 3 123
4
foo = 123; 5
x = &foo;
...
...
x 81345 3
81346
81347
&foo
In C++ you can get the address of a
variable with the “&” operator.
...
...
• Must always refer to something
– Must be initialized, cannot be changed
Dereferencing operator
• To assign a value to the variable foo through the
pointer variable
– we must use the dereferencing operator *
– E.g
*x=10;
//Changes the vale of foo from 123 to 10
Equivalent to
foo=10;
• You can use the integer x points to in a C++
expression like this:
y = *x + 17;
*x = *x +1;
#include <iostream.h>
int main() {
int *ptr_a, *ptr_b;
int num_c = 4, num_d = 7;
ptr_a = &num_c;
ptr_b = ptr_a;
cout << *ptr_a << " " << *ptr_b << "\n";
ptr_b = &num_d;
cout << *ptr_a << " " << *ptr_b << "\n";
*ptr_a = *ptr_b;
cout << *ptr_a << " " << *ptr_b << "\n";
cout << num_c << " " <<
*&*&*&num_c << "\n";
return 0; }
• The output of this program is:
• 44
• 47
• 77
• 77
More Pointers
• int i = 50;
int j = 75;
int *p1 ; int * p2
p1 = &i ; p2 = & j;
cout << *p1;
p1 = p2 ; *p2 =0;
cout <<*p1;
Assigning a value to a
dereferenced pointer
A pointer must have a value before you can
dereference it (follow the pointer).
int *x;
int a[10];
x = &a[2]; x is “the address of a[2] ”
for (int i=0;i<3;i++)
x[i]++;
int a[5];
printing an array
void print_array(int a[], int len) {
for (int i=0;i<len;i++)
cout << "[" << i << "] = "
<< a[i] << endl;
}
• Beware
– The newly acquired memory is uninitialized
unless there is a default SomeType
constructor
Examples
int *iptr = new int;
Rational *rptr = new Rational;
Uninitialized int object
iptr —
rptr 0/1
rptr 1/2
The Primary New Form
• Syntax
P = new SomeType [Expression] ;
– Where
• P is a pointer of type SomeType
• Expression is the number of contiguous objects of type
SomeType to be constructed -- we are making a list
– Note
• The newly acquired list is initialized if there is a default
SomeType constructor
R 2/3 0/1
Delete Operators
• Forms of request
delete P; // used if storage
came from new
delete [] P; // used if storage
came from new[]
– Storage pointed to by P is returned to free
store
• P is now undefined
Cleaning Up
int n;
cout << "Enter list size: ";
cin >> n;
int *A = new int[n];
GetList(A, n);
SelectionSort(A, n);
DisplayList(A, n);
delete [] A;