Transcript Pointers

Pointers
CS362
Pointers


A Pointer is a variable that can hold a memory address
Pointers can be used to:
 Indirectly reference existing variables (sometimes simplifies code syntax)
 Reference dynamically allocated memory
 Read and write to binary files
 Create complex data structures (such as linked lists)
Pointers





Pointers holds an address instead of a data value
Used to access memory location where data resides
We say that the pointer “points to” data
Accessing memory via a pointer is called “indirect access”
We’ve used pointers for some time (reference parameters)
Pointers


To declare pointer variables use the “*” character
It is used to both:




Declare a pointer variable
Access the values that the pointer variable points to
In the end, a pointer (or pointer variable) points to (holds
the address of) a variable of a specific data type.
We will use the asterisk to define what type of data the
pointer points to.
Pointers
datatype* variableName;



Asterisk indicates that the variable being declared is of
type pointer-to-something
It is read as “points to datatype”
Asterisk can be at the end of datatype (as shown above),
or at beginning of variable name:
datatype *variableName;

Either works, but be consistent.
Pointers

Example:
float* fptr;


Declares a pointer called fptr that can hold the address
where a float value exists in memory
The pointer can only “point to” a float value (can’t point to
any other data type)
Pointers




Declared constants/variable have a unique starting address
Address indicates the beginning of the memory area
Addresses are assigned upon allocation
The address operator “&” when followed by a variable
name provides the address of a variable
pointerVariableName = &dataVariableName;
Pointers

Example:
float num1, num2;
float* fltPtr;
num1 = 3.5;
fltptr = &num1;



fltptr points to the memory location assigned to num1.
Pointers will always point to a specific type of memory
(based upon the pointer type).
Type of data stored must match the pointer data type.
Pointers


You access the data value pointed to by a pointer using
the de-referencing operator “*” (which is also the indirection operator)
The asterisk followed by the pointer variable name access
the value stored at the pointed-to address
*ptrVariableName

This reads “the value that prtVariableName points to”
Pointers

Example:
num2 = *fltPtr;

num2 now has the value 3.5 stored at its memory location
*fltPtr = 4.6;

(num 2 is assigned the value that fltPtr points to)
(where fltPtr points to (num1) is assigned the value 4.6)
num1 now has the value 4.6 stored at its memory location
Pointers

Pointers can be initialized when declared like any other
variable:
int sum;
int *sPtr = ∑

Creates pointer sPtr and points it to the variable “sum”
*sPtr = 5;

Assign the value 5 to “where sPtr points to” (“sum”)
Pointers



It is always a good idea to initialize pointers when declared
If a pointer does not point to a valid location, it can be
initialized with the null pointer value
NULL means “points to nothing”
float *myPtr = NULL;


To use NULL the <cstddef> library must be included
NOTE: Pointer variables can only store one of two values;
an address or the value NULL
Pointers

Same type pointers may be assigned each other values
int main()
{
float num = 5.5;
float *ftPtr1 = NULL;
float *ftPtr2 = &num;
*ftPtr2 = 4.4;
ftPtr1 = ftPtr2;
cout << fixed << showpoint << setprecision(1);
cout << “Value is “ << *ftPtr1 << endl;
return 0;
}
Pointers

Common Mistake 1:



valid
int *ptr1, *ptr2
invalid
int* ptr1, ptr2
(declares two pointers that point to integers)
(declares a pointer, and an integer variable)
Common Mistake 2:
given : int num; int *ptr;

valid
ptr = &num;

invalid
*ptr = &num;
(ptr points to an integer location which cannot store the
address of num)
ptr = num;
(ptr can only store an address or num, cannot accept
an integer)
Pointers


Pointers can point to any valid data type (including
complex data types)
For example pointer to an array:


When using pointers with arrays the pointer will point to only one
value within the array
The array name is actually a “constant pointer” to the first value in
the array (e.g. a pointer to the subscript 0 element in the array)
Given:
const int MAX = 50; int grades[MAX]; int* gradesPtr;
gradePtr = grades; (gradePtr now points to the first element in the array)
gradePtr = &grades[5]; (gradePtr now points to the 6th element)
Pointers

Warning:


When using pointers to arrays it is the programmer’s responsibility
to ensure that you do not attempt to point past the end of the
array (similar to boundary test)
Most C++ compilers will NOT identify an error in the code if you
attempt to access past the end of the array, but the program will
either crash or obtain strange or garbage values with the program
runs
Pointers


Some math and relational operators can be used with
pointers
For example, you can add units to a pointer



A unit is one storage unit (e.g. size of int, float, char)
Increments the address by size of data type
This can be used to access arrays rather than using the
normal array syntax
Pointers

Array Syntax vs Pointer Syntax
const int MAX = 10;
int numbers[MAX];
int* arrayPtr = numbers; (arrayPtr points to top of array)


accessing a cell using array syntax
numbers[n] where “n” is a valid index value
accessing a cell using pointer syntax
*arrayPtr
*(arrayPtr + n) where “n” does not exceed the array size
Pointers

Array Syntax vs Pointer Syntax



You can use either array or pointer syntax to initialize a pointer
arrayPtr = &number[n]
or
arrayPtr = number + n;
You can use either array or pointer syntax to access an array value
arrayPtr[n] = nn;
or
*(arrayPtr + n) = nn;
The following are equivalent:
int arrayName[MAX];
int* arrayPtr = arrayName;




arrayName == &arrayName[0]
arrayName == arrayPtr
arrayName + index == &arrayName[index]
*(arrayPtr + index) == arrayName[index]
Pointers


You may also use pointers to access records (struct) data
To access the members of a structure



use the de-referencing operator (asterisk)
then select the member using the dot (.) operator
Note: The de-referencing operation must be inside
parenthesis due to low precedence of the de-referencing
operator (the dot operator has a higher precedence)
Pointers

Example:
struct part
{
int partNum;
string description;
float price;
bool inStock;
};
part onePart;
part* partPtr = &onePart;
(*partPtr).price = 6.77; (result is assigned the value 6.77)
Pointers



Using the parentheses, asterisk, and dot can be awkward
Since using pointers and records are so common another
operator was created to simplify access
The member access operator was created:

composed of the dash and greater-than operator (->) (no space)
partPtr->price = 6.77;
Pointers

The advantages of using a pointer become more obvious
with an array of records
const int MAX = 100;
part inventory[MAX];
int num;
part* partPtr = inventory;
for (num = 0; num < MAX; num++) // This initializes all inStock members of all records
{
// in the inventory array to false;
partPtr->inStock = false;
// Note that the line partPtr++; moves the pointer
partPtr++;
// to the next record in the array (for each looping
}
// of the loop)