C++/Pointers

From Wikiversity
< C++
Jump to navigation Jump to search
Subject classification: this is a technology resource.

In C++, pointers are a primitive datatype that reference an object.

What is a pointer?[edit | edit source]

A pointer is a special kind of variable that stores the address in memory of another variable and can be used to manipulate that variable. In general, whenever a variable is used in C++, it must exist somewhere in the host computer's memory and pointers can store the location of a particular variable.

Pointers associate two pieces of information: (1) the memory address, which is the "value" of the pointer itself, and (2) the data type of the variable pointed to, which is the kind of variable located at that address.

Pointers can be dereferenced to access the value of the variable at the pointer's address. For example:

void f(int* p)
{
    // The code "*p" takes the value of the data at location stored in p
    int n = *p;
}

All the data stored in a program is stored in the computer's memory. For example, if a program has a global variable named "numberOfEmployees" that variable has both a value, for example 120 employees, and an address, which is the actual location in the computer's memory where the value is stored.

Declaring pointers[edit | edit source]

Declaring a pointer is similar to declaring a regular variable, although the name is preceded by an asterisk:

  int *ptr; 
  struct coord *pCrd; 
  void *vp;

In the example above, ptr is a pointer to an integer. pCrd is a pointer to a structure named coord. vp is a void pointer, which does not require a specific datatype.

Unlike references, pointers are not guaranteed to be initialized. As such, they should only be used when they are known to point to an existing object.

Arrays[edit | edit source]

An array is a collection of similar data types under the same name. In C++, arrays are declared similar to the following:

  int arr[25];

The above statement declares as static array of 25 elements, which can be accessed individually. Although arr behaves as a pointer, its value cannot be changed as it references a specific region in memory.

Allocating variables[edit | edit source]

In C++, a new object, variable or array can be created using the new operator, and freed with the delete operator.

  int *ptr = new int;
  /* ... */
  delete ptr;

The new operator allocates an object from the heap and optionally initializes it. When you have finished using it, you must delete it. Otherwise, the pointed memory is inaccessible and the result is memory leak.

Referencing variables[edit | edit source]

The & operator is used to reference an object. When using this operator on an object, you are provided with a pointer to that object. This new pointer can be used as a parameter or be assigned to a variable.

Multi dimensional arrays[edit | edit source]

A multidimensional array allows nesting arrays:

  int grid[3][3];

This allocates 3*3 elements in one memory block. Even though arrays behave similarly to pointers, a multidimensional array is not a pointer-to-a-pointer, as shown below.

low address                                                                             high address
┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
│grid                                                                                              │
├────────────────────────────────┬────────────────────────────────┬────────────────────────────────┤
│grid[0]                         │grid[1]                         │grid[2]                         │
├──────────┬──────────┬──────────┼──────────┬──────────┬──────────┼──────────┬──────────┬──────────┤
│grid[0][0]│grid[0][1]│grid[0][2]│grid[1][0]│grid[1][1]│grid[1][2]│grid[2][0]│grid[2][1]│grid[2][2]│
└──────────┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────┘

The objects grid, grid[0] and grid[0][0] is always at the same location (but different types) but the objects of pptr, *pptr, **pptr is at different locations. When evaluating grid[0][0], the array grid (which is an int[3][3]) is first converted to a pointer of type int(*)[3], taking the element at offset 0, and yields an object of int[3], then it is converted to int* again and the element at offset 0 is taken, generating an object of type int& .

Pointer to a pointer[edit | edit source]

A pointer contains a reference to another variable. It may also point to a pointer:

  int **pptr;
┌────┐┌─────┐┌──────┐
│pptr││*pptr││**pptr│
└─┬──┘└─┬─┬─┘└───┬──┘ 
  └─────┘ └──────┘

For pptr[0][0], the address stored in pptr is taken and the address stored in that address is taken and it is the result of the expression.

Linked List[edit | edit source]

This allows for the implementation of a linked list:

struct LinkedListOfIntsNode
{
    int                   value;
    LinkedListOfIntsNode *next_node;
};

Think of a chain of ten LinkedListOfIntsNode, each pointing to its neighbor to the right. You can traverse the list using next_node.

Pointer to a function[edit | edit source]

A pointer contains a reference. It may also point to a function:

 /* Declaration */
 void (*fp)();

 /* Initialization */
 void foobar()
 {
     std::cout << "Hello from foobar()" << std::endl;
 }
 
 fp = &foobar;
 
 /* Use */
 fp();

Where To Go Next[edit | edit source]

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science