The Psychology of Quality and More |
CHAPTER 9 : Data Usage
9.7 Using ArraysArrays are bounded, ordered sets of data, any element of which may be directly accessed via indexing. They are commonly used to contain data which requires structured access. Arrays are more complex to used than pointers, in that there are two elements to any object reference: the array name and the index. This may actually help the reader, as it gives more information about what is being referenced and why, than a single pointer:
PersonName[Letter] ..contains more information than.. *PersonName ------------------------------------------------------------------- Using an array plus index may be less efficient than a pointer with autoindexing, especially within a loop. However, the loss in performance is usually negligible, and is well worth the improvement in clarity. It is also easier to check that array addressing is within bounds, enabling better defensive programming. Initializing arraysIn (possibly multidimensional) arrays, it is being explicit to declare the size of all dimensions:
char DayName[DAYS_IN_WEEK][MAX_DAY_NAME_LEN] = { "Monday",...
In practice it may be preferable to allow the compiler to determine the final array size of initialized arrays. This simplifies the declaration, avoiding, in this case, the awkwardness of having to know the maximum number of characters in a day name:
char DayName[DAYS_IN_WEEK][] = { "Monday",...
Going one step further, it can be simpler to use arrays of pointers rather than two-dimensional arrays. This simplifies the declaration, minimizes memory requirements and can simplify usage (for example in sorting):
char *DayName[] = { "Monday",...
Note that such string constants should not be modified. Although arrays may be only partially initialized, it is being explicit to complete the initialization, once started:
int SmallSquare[2][2] = { {1}, {1, 0} }; /* incomplete
initialization */ ----------------------------------------------------------------------------- Complexity of arrays increases with the number of dimensions and with the complexity of the index expression. As with any multi-part object reference, they should be used with care.
|
Site Menu |
Quality: | Quality Toolbook | Tools of the Trade | Improvement Encyclopedia | Quality Articles | Being Creative | Being Persuasive | |
And: | C Style (Book) | Stories | Articles | Bookstore | My Photos | About | Contact | |
Settings: | Computer layout | Mobile layout | Small font | Medium font | Large font | Translate | |
You can buy books here |
And the big |