Page 76 - PowerPoint Presentation
P. 76
CAVITE STATE UNIVERSITY
T3 CAMPUS
Department of Information Technology DCIT 25 – Data Structures and Algorithms
Now let’s suppose you want to copy the contents of grade to the oldGrade variable,
but you only want to use the ptGrade pointer. You do this by dereferencing the ptGrade
pointer variable using the asterisk (*) as the dereferencing pointer operator is shown here:
char oldGrade = *ptGrade;
The previous statement tells the computer to go to the memory address contained in
the ptGrade pointer variable and then perform the assignment operation, which copies the
value of memory address 2 to the memory address represented by the oldGrade variable,
which is memory address 1. The result is shown in the next figure.
You can dereference a pointer variable any time you want to use the contents of the
memory address pointed to by the variable and use the dereference pointer variable in any
statement that you would use a variable.
Memory allocated after the contents of the memory address pointed to by ptGrade is copied
to the oldGrade variable
Pointer Arithmetic
Pointers are used to step through memory sequentially by using pointer arithmetic and
the incremental (++) or decremental (--) operator. The incremental operator increases the
value of a variable by 1, and the decremental operator decreases the value of a variable by 1.
In the following example, the value of the studentNumber variable is incremented by
1, making the final value 1235.
int studentNumber = 1234;
studentNumber++;
Likewise, the next example decreases the value of the studentNumber variable by 1,
resulting in the final value of 1233.
int studentNumber = 1234;
studentNumber--;
Pointer arithmetic uses the incremental and decremental operator in a similar but
slightly different way. The following statements declare two variables used to stored student
numbers and two pointers each pointing to one of those variables.
int studentNumber1 = 1234;
int studentNumber2 = 5678;
int *ptStudentNumber1;
int *ptStudentNumber2;
ptStudentNumber1 = &studentNumber1;
ptStudentNumber2 = &studentNumber1;
Page | 23