Pointers/Memory Allocation   «Prev 

Dynamic Array Dissection in C++

Let us dissect this program and examine how new and delete are used.

#include <iostream.h>
#include <assert.h>

//Use of new to dynamically allocate an array
int main(){
  int* data;
  int  size;
    
  cout << "\nEnter array size: ";
  cin >> size;
  assert(size > 0);
    
  data = new int[size];
  assert(data);       //data != 0 allocation succeeds
  for (int j = 0; j < size; ++j)
    cout << (data[j] = j) << '\t';
  cout << "\n\n";
  delete []data;      //deallocate an array
  return (0);
}

int*  data;
int   size;

cout << "\nEnter array size: ";
cin >> size;
assert(size > 0);
data = new int[size];
assert(data);  //data != 0 allocation succeeds


  1. The pointer variable data is used as the base address of a dynamically allocated array whose number of elements is the value of size.
  2. The user is prompted for the integer value size.
  3. The new operator is used to allocate storage from free store capable of storing a variable of type int[size].
  4. On a system where integers take 2 bytes, this would allocate 2 x size bytes. At this point, data is assigned the base address of this store.
  5. The second assert guarantees that allocation succeeded.
  6. In newer C++ systems, when the new operator fails, an exception is thrown and the program is automatically aborted.

for (int j = 0; j < size; ++j)
   cout << (data[j] = j) << '\t';

This statement initializes the values of the data array and prints them.
delete []data;

The operator delete returns the storage associated with the pointer variable data to free store. This can be done only with variables allocated by new. The brackets form is used because the corresponding allocation was of an array.