Arrays are defined in much the same manner as ordinary variables, except that each array name must be accompanied by a size specification (i.e the number of elements).For a one-dimension array, the size is specified by a positive integer expression, enclosed in square brackets.The expression is usually written as a positive integer constatnt.
In general terms, a one-dimensional array definition may be expressed as
storage-class data-type array[ expression];
where storage-class refers to the storage class of the array,data-type is the data type, array is the array name, and expression is a positive-valued integer expression which indicates the number of array elements.The storage-class is optional;default values are automatic for arrays that are defined within a function or a block, and external for arrays that are defined outside of a function.
Several typical one-dimensional array definitions are shown below.
int x[100];
char text[80];
static char message[25];
static float n[12];
The first line states that x is a 100-element integer array, and the second defines text to be an 80-element character array.In the third line,message is defined as a static 25-element character array, whereas the fourth line establishes n as a static 12-element floating-point array.
Automatic arrays, unlike automatic variables, cannot be initialized.However, external and static array definitions can include the assignment of initial value if desired.The initial values must appear in the order in which they will be assigned to the individual array elements, enclosed in braces and separated by commas.The general form is
storage-class data-type array[expression]= {value1,value2,....,value n};
where value 1 refers to the value of the first array element,value 2 refers to the value of the second array element, and so on.The appearance of the expression, which indicates the number of array elements, is optional wen initial values are present.
Consider the following array definitions.
int digits[10] = {3, 3, 3};
static float x[6] = {-0.3, 0, 0.25};
The results, on an element-by-element basis, are as follows.
digits[0] = 3 x[0] = -0.3
digits[1] = 3 x[1] = 0
digits[2] = 3 x[2] = 0.25
digits[3] = 0 x[3] = 0
digits[4] = 0 x[4] = 0
digits[5] = 0 x[5] = 0
digits[6] = 0
digits[7] = 0
digits[8] = 0
digits[9] = 0
In each case, all of the array elements are automatically set to zero except those that have been explicitly initialized within the array definitions.
The array size need not be specified explicitly when initial values are included as a part of an array definition.With a numerical array, the array size will automatically be set equal to the number of initial values included within the definition.
For example,
int digits[10] = {3, 3, 3};
static float x[6] = {-0.3, 0, 0.25}; can also be written as
int digits[ ] = {3, 3, 3};
static float x[ ] = {-0.3, 0, 0.25};
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment