CPP Understanding Pointers

What is a C++ Pointer?

  • Each variable in a C++ program has an byte address in the RAM and occupies a number of bytes depending on the type of the variable.
  • Usually, as a programmer, you don't need to know the particular address of any given variable because the compiler handles the details.

Using address-of operator

  • If you want this information, though, you can use the address-of operator (&), which returns the address of an object in memory.
    Examples of address-of operator (&):
    Source code Result
    #include <iostream>
    using namespace std;
    int main() {
        int rats = 101;
        cout << "rats = " << rats << "\n";
        cout << "rats address = " << &rats << "\n";
        return 0;
    rats = 101
    rats address = 001EFC4C

    You can download this example here (needed tools can be found in the right menu on this page).

  • You can store a Variable's Address in a Pointer.
    int * pRats = 0; // pRats is a pointer to integer
  • This declares pRats to be a pointer to an int. That is, pRats is declared to hold the address of an integer.
  • Many programmers follow the convention of naming all pointers with an initial p, as in pRats, pAge or pNumber
    unsigned short int oldNumber = 50;       // make a variable
    unsigned short int * pNumber = &oldNumber;  // make a pointer to oldNumber
  • pNumber is a pointer that now contains the address of the oldNumber variable

Using the asterisk (*)

  • The asterisk (*) is used in two distinct ways with pointers:
    1. as part of a pointer declaration
    2. and also as a dereference operator.
    unsigned short int oldNumber = 50;       // make a variable
    // The next is a pointer declaration which you read as "int *" 
    // You must read asterisk (*) as related to the type (int) 
    unsigned short int * pNumber = &oldNumber;  // make pointer to oldNumber
    unsigned short int myNumber;
    // The next two statements uses dereference operator 
    // You must now read The asterisk (*) as related to the pointer variable
    // The return value is the value of what the pointer points to 
    myNumber = * pNumber;
    // which also can be changed       
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.