Assigning Values Through a Pointer


1.Assigning Values Through a Pointer

You can use a pointer on the left side of an assignment statement to assign a value to the location pointed to by the pointer. Assuming that p is an integer pointer, this assigns the value 101 to the location pointed to by p:
*p = 101;
You can verbalize this assignment like this: "at the location pointed to by p, assign the value 101." To increment or decrement the value at the location pointed to by a pointer, you can use a statement like this:
(*p)++;

The parentheses are necessary because the * operator has lower precedence than the ++ operator.
The following program demonstrates assignment using a pointer.
// POINTER2.cpp : Defines the entry point for the console application.
//

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

int _tmain(int argc, _TCHAR* argv[])
{
            int *p, num;
            p = &num;
            *p = 100;
            cout << num << ' ';
            (*p)++;
            cout << num << ' ';
            (*p)--;
            cout << num << '\n';
            return 0;
}

The output from the program is shown here.

Share on Google Plus