CP2001 Data Structures and Algorithms
More Basic Concepts in C++

Page 2 of 6

up
Start
prev
Back
next
Next

Pointers and Dynamic Memory

Chpt 14.2
Up to now we have been implementing some basic data structures (like a list of integers) using an (static) array.

This was shown in the Array class file: array.h (see Chapter 10.5 for details), where the constant MAX_ARRAY_SIZE defines the array size.

To be able to manipulate data structures with more flexibility, we have to be able to change the size of data structures at run-time.
To do this we use the system's dynamic memory (called the heap),

To reserve "chunks" of dynamic memory, we need the reserved word new.

To access the different parts of allocated dynamic memory, we need a pointer.

A pointer "points" to a particular base type. For example,

	int *ptr_to_int;
defines the variable ptr_to_int to be a pointer to type int.
The pointer variable contains the address of the variable it's pointing to.

Initially, ptr_to_int points to nothing (ie, contains the value NULL):

Program memory map

We can't actually do much with a pointer until we allocate (heap) memory space for the data type the pointer is pointing to.
To allocate heap memory, we use the new reserved word:

	ptr_to_int = new int;

Program memory and heap memory maps

and to store an int value, we use the dereferencing operator (*):

	*ptr_to_int = 10;  //store integer value 10

Program memory and heap memory maps

Note that we can also allocate memory for a (variable) array:

We can also set up a pointer to a declared variable by storing its address as a pointer value - by using the addressing operator "&":

	int int_val = 3;
	int *int_ptr;
	...
	int_ptr = &int_val; //int_ptr now points to the value 3
	...

We can also access members of a class that is being pointed at:

To use pointer parameters in functions:

Dynamic Memory Management

When you have finished using the heap memory for pointer variables, you should deallocate (free up) the memory.

To free up memory, use the delete reserved word.

	// Allocate dynamic memory
	int *ptr = new int;
	...
	// Free up memory
	delete ptr;

Copyright © 1998 Olivier de Vel. All rights reserved.
prev
Back
next
Next