Pointer
• A pointeris a variable that stores the memory address of an object.
• Pointers are used extensively in both C and C++ for three main purposes:
– to allocate new objects on the heap
– to pass functions to other functions
– to iterate over elements in arrays or other data
• Pointer declarations
– * indicates the declared variable is a pointer
int *myPtr;
declares pointer to int, pointer of type int *
– Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2
5.
Pointer
• Can declarepointers to any data type
• Pointer initialization
– Initialized to 0, NULL, or address
– 0 or NULL points to nothing
– int* intPrt = NULL;
– float* floatPtr = 0;
void main()
{
int x = 5;
int* xPtr;
xPtr = &x;
cout << xPtr << endl;
}
xPtr
x
xPtr
500000 5
x
600000 500000
address of x
is value of
xPtr
5
6.
Pointer
• * (indirection/dereferencing operator)
– Value of the variable pointed by
– Contents of
– *xPtr returns x (because xPtr points to x).
• * and & are inverses of each other
7.
Pointer
// Using the& and * operators.
#include <iostream>
Using namespace std;
void main()
{
int a; // a is an integer
int *aPtr; // aPtr is a pointer to an integer
a = 7;
aPtr = &a; // aPtr assigned address of a
cout << "The address of a is " << &a << "nThe value of aPtr is " << aPtr;
cout << "nnThe value of a is " << a << "nThe value of *aPtr is " << *aPtr;
}
8.
Pointer
• A pointeris a variable that holds the address of something else (variable).
int foo;
int *x;
foo = 123;
x = &foo;
...
...
MEMORY
0
1
2
3
4
5
81345
81346
81347
Address
9.
Pointer
• A pointermust have a value before you can dereference it (follow the pointer).
int *x;
*x=3;
int foo;
int *x;
x = &foo;
*x=3;
ERROR!!!
x doesn’t point to anything!!!
this is fine
x points to foo
10.
Pointer Expressions andPointer
Arithmetic
• Pointer arithmetic
– Increment/decrement pointer (++ or--)
– Add/subtract an integer to/from a pointer( + or += ,- or-=)
– Pointers may be subtracted from each other
– Pointer arithmetic meaningless unless performed on pointer to array
• Pointer assignment
– Pointer can be assigned to another pointer if both of same type
– If not same type, cast operator must be used
11.
Example
int myArray[5] ={7,5,8,7,9};
int* intPtr = &myArray[0];
//int* intPtr = myArray;
/*The array variable holds the address of
first element of array*/
cout << intPtr << endl; // address of 7
cout << myArray << endl; // address of starting location of
array
for (int index = 0; index < 5; index++)
cout << &myArray[index] << " ";
cout << endl;
for (int index = 0; index < 5; index++)
cout << &intPtr[index] << " ";
pointer variable
intPtr
v[0] v[1] v[2] v[4]
v[3]
3000 3004 3008 3012 3016
location
*(intPtr+2)
*(intPtr+4)
12.
Pointer Expressions andPointer
Arithmetic
• Pointer comparison
– Use equality and relational operators
– Comparisons meaningless unless pointers point to members of same array
– Compare addresses stored in pointers
– Example: could show that one pointer points to higher numbered element of array than
other pointer
– Common use to determine whether pointer is 0 (does not point to anything)
13.
Relationship Between Pointersand
Arrays
• Arrays and pointers closely related
– Array name like constant pointer
– Pointers can do array subscripting operations
• Accessing array elements with pointers
– Element b[ n ] can be accessed by *( bPtr + n )
– Called pointer/offset notation
– Addresses
– &b[ 3 ] same as bPtr + 3
– Array name can be treated as pointer
– b[ 3 ] same as *( b + 3 )
• Pointers can be subscripted (pointer/subscript notation)
– bPtr[ 3 ] same as b[ 3 ]
14.
Example
// Using subscriptingand pointer notations with arrays.
#include <iostream>
using namespace std;
int main()
{
int b[] = { 10, 20, 30, 40 };
int *bPtr = b; // set bPtr to point to array b & output array b using
array subscript notation
cout << "Array b printed with:n" << "Array subscript notationn";
for ( int i = 0; i < 4; i++ )
cout << "b[" << i << "] = " << b[ i ] << 'n';
15.
// output arrayb using the array name and ; pointer/offset notation
cout << "nPointer/offset notation where " << "the pointer is the array namen";
for ( int offset1 = 0; offset1 < 4; offset1++ )
cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << 'n';
// output array b using bPtr and array subscript notation
cout << "nPointer subscript notationn";
16.
// output arrayb using the array name and ; pointer/offset notation
cout << "nPointer/offset notation where " << "the pointer is the array namen";
for ( int j = 0; j < 4; j++ )
cout << "bPtr[" << j << "] = " << bPtr[ j ] << 'n’ << "nPointer/offset notationn";
// output array b using bPtr and pointer/offset notation
for ( int offset2 = 0; offset2 < 4; offset2++ )
cout << "*(bPtr + " << offset2 << ") = “ << *( bPtr + offset2 ) << 'n';
return 0; // indicates successful termination
} // end main
Memory Allocation
Static memory
Usingdefinitions and declarations
{
float a=0.0;
int b[200];
char c=‘Y’;
…
}
Dynamic Memory
• Using predefined functions
– new
– Delete
int* ptr;
ptr = new int[200];
delete [] ptr;
19.
Dynamic Memory Allocation
•Variables are accessed indirectly via a pointer variable
• Memory space is explicitly allocated (using new)
• Space is allocated from an area of run-time memory known as the heap
• In C++ space must be explicitly returned (using delete) to avoid “memory leak”
• C++ programmers are responsible for memory management
20.
Declaring a pointervariable
Variables are accessed indirectly via a pointer variable
• Syntax
– <data type> * <pointer name>;
• examples
– int * intPointer;
21.
Assigning a valueto a pointer
variable
The value of a pointer variable is a memory address
• Assign address of an existing variable
– int number;
– intPointer = &number;
• Use "new" to allocate space in the heap
– intPointer = new int;
– Address of heap memory space allocated becomes the value of the pointer
variable
22.
Dereferencing a pointervariable
Heap variables do not have a name of their own
– Anonymous variables
*intPointer refers to the value pointed to by intPointer
what happens?
– intPointer = 36;
– *intPointer = 36;
– cout << *intPointer;
– intPointer = null;
23.
Return the allocatedspace/
Deleting the pointer
Done by using the delete statement
• Syntax
– delete <pointer variable>;
• example
float* fPointer = new float;
cin >> (*fPointer);
delete fPointer;
24.
Intializing the allocatedspace
Using the basic format (new Type), the resulting space is not initialized
If you add an empty pair of parentheses (), the space is initialized to 0.
If you add a pair of parentheses with an appropriate value in between (val), the
space is initialized to val.
Examples
int* i1ptr = new int; // new space, ? val
int* i2ptr = new int(); // new space, 0 val
int* i3ptr = new int(42); // new space, 42 val
25.
Allocating a 1-DimensionalArray
Use square brackets, size after type in new:
new Type[rows]
Variable should be a pointer to type Type
Example:
– int size = 10;
– int* iarray = new int[size];
– float* farray = new float[size * 2];
26.
Releasing a 1-DimensionalArray
To release 1-dimensional array use delete, but put [] between keyword delete
and pointer:
– delete [] aptr;
The brackets inform to C++ that you are giving back a group of memory
Example:
– int* iarray = new int[10];
– delete[] iarray;
27.
Example: 1-Dimensional Array
intsize;
cout << "Enter size of array : ";
cin >> size;
int *myArray = new int[ size ];
for ( int index = 0; index < size; ++index)
cin >> myArray[index];
for (int index = 0; index < size; ++index)
cout << setw(5) << myArray[index];
// ... and then delete the pointer array itself:
delete [] myArray;
28.
Example: 2-Dimensional Array
intn_ rows;
int n_ columns;
cout << "Enter number of Rows : ";
cin >> n_rows;
cout << "Enter number of Columns : ";
cin >> n_columns;
// Allocate an array of rows pointers to int:
int **matrix = new int * [ n_rows ];
// The row array pointers are initialised to rubbish. We have to allocate an array of
column elements for each row:
for ( int row = 0; row < n_rows; ++row )// Allocate the column array for this row:
matrix[row] = new int[n_columns];
29.
Example: 2-Dimensional Array
for(int row = 0; row < n_rows; ++row)
{
for (int col = 0; col < n_columns; ++col)
{
cin >> matrix[row][col];
}
}
for (int row = 0; row < n_rows; ++row)
delete[] matrix[row];
// ... and then delete the row pointer array itself:
delete [] matrix;