Step 2: Variable Length Arrays
In C++ and pre-C99 dialects of C, an array's dimension must be a
constant integral expression so that its size can be calculated at compile-time. In
C99 this rule was relaxed. Now an array's dimension must be an
integral expressionnot necessarily a constant one. This allows you to declare a
variable-length array, which is an array whose dimension(s) are determined at runtime. Here is an example:
void func(int dim)
{
int arr[dim]; // dim isn't a constant; C99 only
cout<< sizeof (arr) <<endl;
}
The
arr may have different dimension in every
func() call. For example:
int main()
{
size_t elements;
cout<<"how many elements? "<<endl;
cin>> elements;
func(elements);
}
Most compilers require that you turn on C99 support explicitly to use this feature. For example, in
GCC you need to use the "
-std=c99" command option. The C99 standard also modifies the semantics of the
sizeof operator. When applied to variable length arrays, it computes their size at runtime. This is why the
cout expression inside
func() displays the correct size of
arr on every invocation.
A Different Dimension
The array_wrapper class doesn't replace
st::vector; rather, it serves as an efficient, STL-compatible wrapper for built-in arrays. C99's variable length arrays are another variant of the traditional built-in arrays. The only difference is that in this case the array's dimension is determined at runtime. In modern operating systems, a typical process has a stack size of 2 MB, which makes variable length arrays more useful than they would have been in the days of 16-bit computing. Think for example of a thumbnail viewer that reads an image from a disk file. Instead of mucking with dangling pointers, memory leaks,
delete versus
delete[] and exception handling, you can read the size of each image from the disk, create a variable length array of the appropriate size and be done. This feature is particularly appealing to C programmers, although C++ programmers can also add it to their arsenal.