Sunday, September 26, 2010

Unsized Array Initializations in C,C++

Imagine that you are using array initialization to build a table of error messages, as
shown here:
char e1[12] = "Read error\n";
char e2[13] = "Write error\n";
char e3[18] = "Cannot open file\n";
As you might guess, it is tedious to count the characters in each message manually
to determine the correct array dimension. Fortunately, you can let the compiler automatically calculate the dimensions of the arrays. If, in an array initialization
statement, the size of the array is not specified, the C/C++ compiler automatically
creates an array big enough to hold all the initializers present. This is called an unsized
array. Using this approach, the message table becomes
char e1[] = "Read error\n";
char e2[] = "Write error\n";
char e3[] = "Cannot open file\n";
Given these initializations, this statement
printf("%s has length %d\n", e2, sizeof e2);
will print
Write error has length 13
Besides being less tedious, unsized array initialization allows you to change any of the
messages without fear of using incorrect array dimensions.
Unsized array initializations are not restricted to one-dimensional arrays. For
multidimensional arrays, you must specify all but the leftmost dimension. (The other
dimensions are needed to allow the compiler to index the array properly.) In this way,
you may build tables of varying lengths and the compiler automatically allocates
enough storage for them. For example, the declaration of sqrs as an unsized array is
shown here:
int sqrs[][2] = {
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};
The advantage of this declaration over the sized version is that you may lengthen or
shorten the table without changing the array dimensions.

No comments:

Post a Comment