POINTER OPERATIONS


1.1.The Pointer Operators

There are two special operators that are used with pointers: * and &. The & is a unary operator that returns the memory address of its operand. (Recall that a unary operator requires only one operand.) For example,
balptr = &balance;
puts into balptr the memory address of the variable balance. This address is the location of the variable in the computer’s internal memory. It has nothing to do with the value of balance. The operation of & can be remembered as returning "the address of" the variable it precedes. Therefore, the above assignment statement could be verbalized as "balptr receives the address of balance." To better understand this assignment, assume that the variable balance is located at address 100. Then, after the assignment takes place, balptr has the value 100.
The second operator is *, and it is the complement of &. It is a unary operator that returns the value of the variable located at the address specified by its operand. Continuing with the same example, if balptr contains the memory address of the variable balance, then
value = *balptr;
will place the value of balance into value. For example, if balance originally had the value 3,200, then value will have the value 3,200, because that is the value stored at location 100, the memory address that was assigned to balptr. The operation of * can be remembered as "at address." In this case, then, the statement could be read as "value receives the value at address balptr." Figure 6-1 depicts the actions of the two preceding statements.
// STRING12.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
            int balance;
            int *balptr;
            int value;
            balance = 3200;
            balptr = &balance;
            value = *balptr;
            cout << "balance is:" << value << "\n";
            return 0;
}

The output is shown in next picture.

It is unfortunate that the multiplication symbol and the "at address" symbol are the same. This fact sometimes confuses newcomers to the C++ language. These operators have no relationship to each other. Keep in mind that both & and * have a higher precedence than any of the arithmetic operators except the unary minus, with which they are equal. The act of using a pointer is often called indirection, because you are accessing one variable indirectly through another variable.
Share on Google Plus