Jasinski Technical Wiki


Home Page
All Pages

Quick Search
Advanced Search »

Contributor Links

Create a new Page
File Management
Your Profile

Other Wiki Sections



C++ Pointers and References

Modified on Tue, Jan 27, 2009, 10:08 PM by Administrator Categorized as C and C-plus-plus


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


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


*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

  • Unary operator that gives the number of bytes occupied by the operand
  • To calculate number of elements in an array, assuming all the elements are the same size, use: (sizeof var) / (sizeof var[0])

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


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

  • To allocate heap space, use the new keyword: pvalue = new double;
  • Be sure to handle error conditions

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

  • To avoid memory leaks, use the delete keyword when done with the pointer.


  • Definition - An alias for another variable. Similar to pointers, but not the same thing
  • Declaration - datatype& refname = varname;
  • Use - Operations on refname are identical to operations on varname

ScrewTurn Wiki version Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2023, Patrick Jasinski.