Cpp - Pointers, Addresses, and Variables

Introduction

A pointer involves three concepts:

  • a pointer
  • the address that the pointer holds, and
  • the value at the address held by the pointer.

Consider the following code fragment:

int theVariable = 5; 
int *pPointer = &theVariable; 

theVariable is declared to be an integer variable initialized with the value 5.

pPointer is declared to be a pointer to an integer; it is initialized with the address of theVariable.

The address that pPointer holds is the address of theVariable.

The value at the address that pPointer holds is 5.

Manipulating Data by Using Pointers

After a pointer is assigned the address of a variable, you can use that pointer to access the data.

The following code demonstrates how the address of a local variable is assigned to a pointer and how the pointer manipulates the values in that variable.

Demo

#include <iostream> 
 
int main() // w  ww  .j av  a  2s.co m
{ 
    int myAge;                  // a variable 
    int *pAge = nullptr;  // a pointer 
 
    myAge = 5; 
    pAge = &myAge;     // assign address of myAge to pAge 
    std::cout << "myAge: " << myAge << "\n"; 
    std::cout << "*pAge: " << *pAge << "\n\n"; 
 
    std::cout << "*pAge = 7\n"; 
    *pAge = 7;         // sets myAge to 7 
    std::cout << "*pAge: " << *pAge << "\n"; 
    std::cout << "myAge: " << myAge << "\n\n"; 
 
    std::cout << "myAge = 9\n"; 
    myAge = 9; 
    std::cout << "myAge: " << myAge << "\n"; 
    std::cout << "*pAge: " << *pAge << "\n"; 
 
    return 0; 
}

Result

This program declares two variables: an int myAge and a pointer pAge, which is a pointer to an int and holds the address of myAge.

myAge is assigned the value 5; this is verified by the output.

Related Topic