Pointer Variable Declarations and Initialization
Pointer variables contain memory address as their values.
Diagrams typically represent a pointer as an arrow from the variable that contains an address to the variable located at that address in memory.
int *countPtr;
Pointer should be initialized to 0, NULL or an address of the corresponding type either when they're declared or in an assignment.
A pointer with the value 0 or NULL "points to nothing" and is known as a null pointer.
Pointer Operators
The address operator(&) is a unary operator that obtains the address memory address of its operand.
int y = 5; // declare variable y
int *yPtr; // declare pointer variable yPtr
yPtr = &y; // assign address of y to yPtr
Now, yPtr indirectly references variable y's value.
The * operator, commonly referred to as the indirection operator or dereferencing operator.
indirection operator
int y = 1;
int *yPtr = &y;
the value of yPtr is address of variable y.
dereferencing operator
*yPtr = 9;
would assign 9 th variable y.
Pointer and Array
Assume the following declarations:
int b[5]; // create 5-element int array b
int *bPtr; // create int pointer bPtr
Because the array name is a pointer to the first element of the array, we can set bPtr to the address of the first element in array b with the statement
bPtr = b; // assign address of the array b to bPtr
also
bPtr = &b[0]; // also assigns address of array b to bPtr
Example
#include <iostream>
using namespace std;
int main()
{
int b[] = {10, 20, 30, 40}; // create 4-element array b
int *bPtr = b; // set bPtr to point to array b
// output array b using array subscript notation
cout << "Array b printed with:
Array subscript notation
";
for (int i = 0; i < 4; i++)
{
cout << "b[" << i << "] = " << b[i] << "
";
}
// out array b using the array name and pointer/offset notation
cout << "
Pointer/offset notation where "
<< "the pointer is the array name
";
for (int offset1 = 0; offset1 < 4; offset1++)
{
cout << "*(b + " << offset1 << ") = " << *(b + offset1) << "
";
}
// output array b using bPtr and array subscript notation
cout << "
Pointer subscript notation
";
for (int j = 0; j < 4; j++)
{
cout << "bPtr[" << j << "] = " << bPtr[j] << "
";
}
cout << "
Pointer/offset notation
";
// out array b using bPtr and pointer/offset notation
for (int offset2 = 0; offset2 < 4; offset2++)
{
cout << "*(bPtr + " << offset2 << ") = "
<< *(bPtr + offset2) << "
";
}
}
output:
Array b printed with:
Array subscript notation
b[0] = 10
b[1] = 20
b[2] = 30
b[3] = 40
Pointer/offset notation where the pointer is the array name
*(b + 0) = 10
*(b + 1) = 20
*(b + 2) = 30
*(b + 3) = 40
Pointer subscript notation
bPtr[0] = 10
bPtr[1] = 20
bPtr[2] = 30
bPtr[3] = 40
Pointer/offset notation
*(bPtr + 0) = 10
*(bPtr + 1) = 20
*(bPtr + 2) = 30
*(bPtr + 3) = 40
Program ended with exit code: 0