Chapter Summary

I l @ ve RuBoard

Chapter Summary

An array is a set of elements that all have the same data type. Array elements are stored sequentially in memory and are accessed by using an integer index (or offset). In C, the first element of an array has an index of , so the final element in an array of n elements has an index of n - 1 .

To declare a simple one-dimensional array , use this form:

  type name  [  size  ]; 

Here, type is the data type for each and every element, name is the name of the array, and size is the number of elements.

C interprets the name of an array to be the address of the first element of the array. In other terms, the name of an array is equivalent to a pointer to the first element. In general, arrays and pointers are closely connected. If ar is an array, then the expressions ar[i] and *(ar + i) are equivalent.

C does not enable entire arrays to be passed as function arguments, but you can pass the address of an array. The function can then use this address to manipulate the original array. If the intent of the function is not to modify the original array, you should use the const keyword when declaring the formal parameter representing the array. You can use either array notation or pointer notation in the called function. In either case, you're actually using a pointer variable.

Adding an integer to a pointer or incrementing a pointer changes the value of the pointer by the number of bytes of the object being pointed to. That is, if pd points to an 8-byte double value in an array, adding 1 to pd increases its value by 8 so that it will point to the next element of the array.

Two-dimensional arrays represent an array of arrays. For instance, the declaration

 double sales[5][12]; 

creates an array sales having five elements, each of which is an array of 12 doubles . The first of these one-dimensional arrays can be referred to as sales[0] , the second as sales[1] , and so on, with each being an array of 12 int s. Use a second index to access a particular element in these arrays. For instance, sales[2][5] is the sixth element of sales[2] , and sales[2] is the third element of sales .

We've used int arrays and double arrays in this discussion, but the same concepts apply to other types. Character strings, however, have many special rules. This stems from the fact that the terminal null character in a string provides a way for functions to detect the end of a string without being passed a size. We will look at character strings in detail in Chapter 11, "Character Strings and String Functions."

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net