C++ style dynamic size arrays (new[] and delete[])

It probably occurred to you that we won't always know the size of an array at the start of a program. We would need to allocate the array's size dynamically.

However, if you've tried it, you might have noticed that this doesn't work!

Let's try and use the cin command to take in an array size from the user. Let's ask the user how big he wants his array and try to create one for him of that size:

#include <iostream>
using namespace std;
int main()
{
  cout << "How big?" << endl;
  int size;       // try and use a variable for size..
  cin >> size;    // get size from user
  int array[ size ];  // get error: "unknown size"
}

We get the following error:

error C2133: 'array' : unknown size

The problem is that the compiler wants to allocate the size of the array. However, unless the variable size is marked const, the compiler will not be sure of its value at compile time. The C++ compiler cannot size the array at compile time, so it generates a compile time error.

To fix this, we have to allocate the array dynamically (on the "heap"):

#include <iostream>
using namespace std;
int main()
{
  cout << "How big?" << endl;
  int size;       // try and use a variable for size..
  cin >> size;
  int *array = new int[ size ];  // this works
  // fill the array and print
for( int index = 0; index < size; index++ )
{
  array[ index ] = index * 2;
  cout << array[ index ] << endl;
}
delete[] array; // must call delete[] on array allocated with 
                // new[]!
}

So the lessons here are as follows:

  • To allocate an array of some type (for example, int) dynamically, you must use new int[numberOfElementsInArray].
  • Arrays allocated with new[] must be later deleted with delete[], otherwise you'll get a memory leak! (that's delete[] with square brackets! Not regular delete).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.76.72