C++ Pointers and References

Declaring

datatype *identifier — for example: long *pnum
datatype* identifier — for example: long* pnum

Initializing

pointer = &variable — for example: pnum = &num
pointer = NULL — for example: pnum = NULL — points the pointer at nothing

Dereferencing

*pointer refers to what the pointer points at
For example *pnum = 2 places the value 2 in the address specified by pnum.

Pointer to Char

Can be initialized with a string literal. For example, char *name="John Doe"; The cout routine outputs the string, not its address

Arrays of Pointers

Example: char *pstr[] = {"Tom", "Dick", "Harry"};

The sizeof Operator


Operand Return Value
Data type Bytes consumed by any variable of that datatype
PointerBytes for the pointer - not the bytes consumed by what it points at
Array elementBytes for the specified element
ArrayBytes for the whole array

Constants and Pointers

Description Example Pointer Data
Pointer to a constant const char* pstring="ABC"; can point elsewhere constant
Constant pointer char* const pstring="ABC"; constant can be changed
Constant pointer to a constant const char* const pstring="ABC"; constant constant

Pointers and Arrays

General

double *pdata; 
double data[5]; 
pdata = data; // makes pdata point at array's first element. 

The last statement is equivalent to pdata = &data[0];

Pointer Arithmetic

pdata += 1; // increments pdata to point to the next array element


Using Dereferencing

If pdata is pointing at data[2], the statement *(pdata + 1) = *(pdata + 2) is the same as data[3] = data[4]

Using Array Name Like a Pointer

The syntax data[3] is the same as *(data + 3)

Dynamic Memory Allocation


if (!(pvalue = new double)) 
  cout << "\nOut of memory\n"; 
else 
  { 
  // do useful stuff here 
  }



References