C++ Pointer Address Operators and Pointer Operators

Introduction

Operator Meaning
& (unary) (In an expression) the address of
& (unary) (In a declaration) reference to
* (unary) (In an expression) the thing pointed at by
* (unary) (In a declaration) pointer to

The following Layout program demonstrates how the & operator can be used to display the layout of variables in memory:

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    int  start;/* w  w  w .  j ava 2 s.co  m*/
    int    n; long    l; long long   ll;
    float  f; double  d; long double ld;
    int  end;

    cout.setf(ios::hex);
    cout.unsetf(ios::dec);

    // output the address of each variable in order to get an idea of how variables are laid out in memory
    cout << "--- = " << &start << endl;
    cout << "&n  = " << &n     << endl;
    cout << "&l  = " << &l     << endl;
    cout << "&ll = " << &ll    << endl;
    cout << "&f  = " << &f     << endl;
    cout << "&d  = " << &d     << endl;
    cout << "&ld = " << &ld    << endl;
    cout << "--- = " << &end   << endl;

    return 0;
}



PreviousNext

Related