Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Spruce Up Your Built-in Arrays-3 : Page 3


advertisement
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 expression—not 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.



Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap