Cpp - Pointer Defining Pointers


A pointer represents both the address and type of another object.

You can use the address operator, &, for a given object creates a pointer to that object.

Given that var is an int variable,

&var         // Address of the object var 

is the address of the int object in memory and thus a pointer to var.

A pointer points to a memory address and indicates by its type how the memory address can be read or written to.

Pointer Variables

An expression such as &var is a constant pointer.

C++ can define pointer variables, that is, variables that can store the address of another object.

int *ptr;            // or:  int* ptr; 

This statement defines the variable ptr, which is an int* type, a.k.a, a pointer to int.

ptr can store the address of an int variable.

Point types are derived types.

Objects of the same base type T can be declared together.

int a, *p, &r = a;  // Definition of a, p, r 

After declaring a pointer variable, you must point the pointer at a memory address.


// Prints the values and addresses of variables. 
#include <iostream> 
using namespace std; 

// Definition of variables var and ptr 
int var, *ptr;    

int main()        
{                 /*from  w  w  w  .  ja  va  2 s  .c  om*/
    var = 100; 
    ptr = &var; 
    // Outputs the values and addresses of the variables var and ptr. 

    cout << " Value of var:      " <<  var 
           << "   Address of var: " <<  &var 
           << endl; 
    cout << " Value of ptr: "      <<  ptr 
           << "   Address of ptr: " <<  &ptr 
           << endl; 
    return 0; 


Related Topic