Page 75 - PowerPoint Presentation
P. 75
CAVITE STATE UNIVERSITY
T3 CAMPUS
Department of Information Technology DCIT 25 – Data Structures and Algorithms
Accessing Data Pointer to by a Pointer
A pointer variable references a memory location that contains a memory address.
Sometimes a programmer wants to copy that memory address to another pointer variable.
This is accomplished by using an assignment statement as shown here:
ptOldGrade = ptNewGrade;
You will notice that this assignment statement is identical to assignment statements
used with any variable. Remember that the assignment statement tells the computer to copy
the contents of a variable regardless if the content is a memory address or any other value.
Other times, programmers want to the use of the content of the memory address stored
in the pointer variable. This may be tricky to understand, so let’s look at an example to clear
up any confusion.
The first two statements declare variable, one of which is initialized with a value. The
next two statements declare pointer variable. And the last statement assigns the address of
the first variable to pointer variables.
char oldGrade;
char grade = ‘A’;
char *ptGrade;
char *ptOldGrade;
ptGrade = &grade;
Memory allocated after values are assigned to variables.
Let’s say a programmer wants to use the value stored in the grade variable to display
the grade on the screen. However, the programmer wants to use only the ptGrade pointer to
do this.
The programmer uses the pointer dereferencing (sometimes called the dereferencing
operator), which is the asterisk (*), to dereference the point variable. Think of dereferencing
as telling the computer you are referring to go to the memory address contained in the pointer
and then perform the operation. Without dereferencing, the computer is told to use the
contents of the pointer when performing the operation.
Let’s say you want to copy the content of ptGrade to ptOldGrade. Here’s how you
would do it: ptOldGrade = ptGrade;
Memory allocated after the value of the ptGrade is copied to ptOldGrade
Page | 22