// ex2.cppDownload Example 2
//
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
int * a= new int[10];
int * b=new int(89) ;
cout << "*b=" << *b << endl;
int * c = new (nothrow) int [1000000000];
if (!c)
{
cout << "Failed to allocate memory" << endl;
}
*(a+5)=9;
cout << "a[5]=" << *(a+5) << endl;
delete [] a;
delete b;
delete [] c;
return 0;
}
The array a is allocated space for 10 ints but arrays cannot have an initial value. The int pointer b is allocated space for an int and given an initial value of 89. Next, there is a doomed attempt to allocate a billion ints on my 1GB RAM PC. As an int takes 4 bytes that would require 4GB. Also under 32 bit Windows you are limited to 2GB of RAM.
The (nothrow) prevents an exception occurring and the failed message is almost certain to be displayed, unless you are blessed with a 64 Bit computer and a surfeit of RAM.
The array a is tested by setting and displaying an array element. Just as in C, an array and a pointer can be considered the same-they are addresses. Adding 5 to the pointer is the same as indexing an array by [5].
Finally the three delete statements free up allocated memory. In the case of the filed c variable, freeing up a zero pointer is ok. Note the use of [] for a and c. Forget those on array pointer variables (even char *) and you will experience memory problems.
On the next page : Some Rules for using Pointers

