COMP2115 – INFORMATION STRUCTURES
Lecture Notes
Pointers
Pointers
– A variable that contains the memory address of another variable.
– Powerful, but difficult to master
– Simulate call-by-reference
– Close relationship with arrays and strings
Pointer Variable Declarations and Initialization
Pointer variables
• Pointers contain address of a variable that has a specific value
(indirect reference)
• Contain memory addresses as their values
• Normal variables contain a specific value (direct reference)
• Pointers contain address of a variable that has a specific value
(indirect reference)
• Indirection – referencing a pointer value
Example:
Pointer declarations
– * used with pointer variables
e.g. int *myPtr;
Declares a pointer to an int (pointer of type int *)
– Multiple pointers require using a * before each variable declaration
e.g. int *myPtr1, *myPtr2;
• Can declare pointers to any data type
• Initialize pointers to 0, NULL, or an address
1
• 0 or NULL – points to nothing (NULL preferred)
Pointer Operators
• & (address operator)
Returns address of operand
e.g. int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y; yPtr “points to” y
• * (indirection/dereferencing operator)
Returns a synonym/alias of what its operand points to
*yptr returns y (because yptr points to y)
* can be used for assignment e.g. *yptr = 7; // changes y to 7
Returns alias to an object
Dereferenced pointer (i.e. operand of *) must be an lvalue (no constants).
We can have *yPtr =7 and NOT *7 = yPtr
NB. * and & are inverses – They cancel each other out
2
Using the const Qualifier with Pointers
const qualifier
• Variable cannot be changed
• Use const if function does not need to change a variable
• Attempting to change a const variable produces an error
•
const pointers
• Point to a constant memory location
• Must be initialized when declared
int *const myPtr = &x;
Type int *const – constant pointer to an int
const int *myPtr = &x;
Regular pointer to a const int
const int *const Ptr = &x;
const pointer to a const int
x can be changed, but not *Ptr
EXAMPLE
#include <stdio.h>
int main()
{
int x, y;
int * const ptr = &x; /* ptr is a constant pointer to an integer. An integer
can be modified through ptr, but ptr always points
to the same memory location. */
*ptr = 7;
ptr = &y;
return 0;
}
Program Output
Error: TestPointer.cpp(11,9): Cannot modify a const object in function main
*** 1 errors in Compile ***
3
sizeof Function
sizeof
o Returns size of operand in bytes
o For arrays: size of 1 element multiplied by number of elements
e.g.
if sizeof( int ) equals 4 bytes, then
int myArray [10];
cout << sizeof (myArray );
will print 40
i.e 4 bytes times 10 elements
sizeof can be used with
Variable names
Type name
Constant values
Pointer Program Example: Bubble Sort Using Call-by-reference
Implement bubblesort using pointers
Swap two elements
swap function must receive address (using &) of array elements
Array elements have call-by-value default
Using pointers and the * operator, swap can switch array elements
Psuedocode
Initialize array
print data in original order
Call function bubblesort
print sorted array
Define bubblesort
Example
#include <stdio.h>
#define SIZE 10
void bubbleSort( int *, const int );
int main()
4
{
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int i;
cout << "Data items in original order << “\n";
for ( i = 0; i < SIZE; i++ )
cout << a[ i ] << “ ”;
bubbleSort( a, SIZE ); /* sort the array */
cout << “\n” << “Data items in ascending order” << “\n”;
for ( i = 0; i < SIZE; i++ )
cout << a[ i ] << “ ”;
cout << “\n”;
return 0;
}
void bubbleSort( int *array, const int size )
{
void swap( int *, int * );
int pass, j;
for ( pass = 0; pass < size - 1; pass++ )
for ( j = 0; j < size - 1; j++ )
if ( array[ j ] > array[ j + 1 ] )
swap( &array[ j ], &array[ j + 1 ] );
}
void swap( int *element1Ptr, int *element2Ptr )
{
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}
Program Output:
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89
5
Pointer Expressions and Pointer Arithmetic
Arithmetic operations can be performed on pointers
Increment/decrement pointer (++ or --)
Add an integer to a pointer( + or += , - or -=)
Pointers may be subtracted from each other
Arithmetic operations are meaningless unless performed on an array
Example:
5 element int array on machine with 4 byte ints
vPtr points to first element v[0] at location 3000 (vPtr = 3000)
vPtr += 2; sets vPtr to 3008
vPtr points to v[2] (incremented by 2), but the machine has 4 byte ints, so
it points to address 3008
Subtracting pointers
Returns number of elements from one to the other.
Example:
vPtr2 = v[2];
vPtr = v[0];
vPtr2 - vPtr would produce 2
Pointer comparison ( <, == , > )
See which pointer points to the higher numbered array element
Also, see if a pointer points to 0 (or NULL)
Pointers of the same type can be assigned to each other
If not the same type, a cast operator must be used
Exception: pointer to void (type void *)
Generic pointer, represents any type
No casting needed to convert a pointer to void pointer
NB: void pointers cannot be dereferenced
6
The Relationship Between Pointers and Arrays
Arrays and pointers are closely related
Array name like a constant pointer
Pointers can do array subscripting operations
Example
Declare an array b[ 5 ] and a pointer bPtr
To set them equal to one another use:
bPtr = b;
The array name (b) is actually the address of first element of the array b[5]
bPtr = &b[0]
Explicitly assigns bPtr to address of first element of b
Element b[3]
Can be accessed by *( bPtr + 3 )
Can also be accessed by bptr[3]
- This is called pointer/subscript notation. In other words:
bPtr[3] is the same as b[3]
Can be accessed by performing pointer arithmetic on the array itself:
*( b + 3 )