------------------------------------------------------------------------------
MC logo
Dynamic Arrays
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Dynamic Array Allocation]

How Big Do You Want That Array, Sir?

In Java, arrays are allocated with new, with an expression to give the size. This expression can be constant or variable. In C and and C++, the situation is far too interesting.

Generally, you should write to the standards and not use a variable size in an array declaration. The standard way to do this in C++ is to allocate the array with new. For an integer variable n (or any integer expression):
int *fred = new int[n];
...
delete [] fred;
The @new@ looks a lot like Java at first, but there are important differences: The lack of garbage collection is a very important difference. Programmers must remember to release memory when they are finished, or it will continue allocated and useless until the program exits.

The C++ libraries, and the language itself, provide some assistance for this task, but it's something you must consider when using dynamic arrays or other dynamically-allocated space.