Basic Arrays
Overview
- An array is a collection of data items, all of the same type, accessed using a common name.
- You may not operate on an entire array at once. The only
way to operate "on an array" is to choose individual elements on which
to perform calculations.
- A one-dimensional array is like a list; A two-dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may.
- Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
Declaring and Allocating Arrays
Very soon, you will need to separate in your mind declaration from allocation.
Declaring a variable means that you specify the name and the type.
Allocating a variable is when the space where that variable will reside is created.
For the variables we've seen so far, those two things happen at the same time. This pairing of the two is about to end.
- Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array.
- Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.
- Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.
- In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allocated only once, at the time the array is declared. The array does NOT change sizes later if the variable used to declare it changes. )
- Examples:
int i, j, intArray[ 10 ], number;
float floatArray[ 1000 ];
int tableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */
const int NROWS = 100; // ( Old code would use #define NROWS 100 )
const int NCOLS = 200; // ( Old code would use #define NCOLS 200 )
float matrix[ NROWS ][ NCOLS ];
C99 Only Example:
int numElements;
printf( "How big an array do you want? " );
scanf( "%d", &numElements; )
if( numElements <= 0 ) {
printf( "Error - Quitting\n" );
exit( 0 );
}
double data[ numElements ]; // This only works in C99, not in plain C
Initializing Arrays
Initializing a variable is placing the first values into that variable.
Often, the safest thing to do is to provide a starting value at the same
time as declaration (and allocation). However, this will soon not be able
to occur in a single line of code. Below are ways to initialize arrays
at the point of declaration and allocation.
- Arrays may be initialized when they are declared, just as any other variables.
- Place the initialization data in curly {} braces following the equals sign. Note the use of commas in the examples below.
- An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero.
- If an array is to be completely initialized, the dimension of the array is not required. The compiler will automatically size the array to fit the initialized data. ( Variation: Multidimensional arrays - see below. )
- Examples:
int i = 5, intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 }, k;
float sum = 0.0f, floatArray[ 100 ] = { 1.0f, 5.0f, 20.0f };
double piFractions[ ] = { 3.141592654, 1.570796327, 0.785398163 };
Designated Initializers:
- In C99 there is an alternate mechanism, that allows you to initialize specific elements, not necessarily at the beginning.
- This method can be mixed in with traditional iniitalization
- For example:
int numbers[ 100 ] = { 1, 2, 3, [10] = 10, 11, 12, [60] = 50, [42] = 420 };
- In this example,the first three elements are initialized to 1, 2, and 3 respectively.
- Then element 10 ( the 11th element ) is initialized to 10
- The next two elements ( 12th and 13th ) are initialized to 11 and 12 respectively.
- Element number 60 ( the 61st ) is initialized to 50, and number 42 ( the 43rd ) to 420.
- ( Note that the designated initializers do not need to appear in order. )
- As with traditional methods, all uninitialized values are set to zero.
- If the size of the array is not given, then the largest initialized position determines the size of the array.
Using Arrays
You may not operate on an entire array at once. The only
way to operate "on an array" is to choose individual elements on which
to perform calculations.
- Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name.
- Array subscripts must be of integer type. ( int, long int, char, etc. )
- VERY IMPORTANT: Array indices start at zero in C, and go to one less than the size of the array. For example, a five element array will have indices zero through four. This is because the index in C is actually an offset from the beginning of the array. ( The first element is at the beginning of the array, and hence has zero offset. )
- Landmine: The most common mistake when working with arrays in C is forgetting that indices start at zero and stop one less than the array size.
- Arrays are commonly used in conjunction with loops, in order to perform the same calculations on all ( or some part ) of the data items in the array.
Sample Programs Using 1-D Arrays
- The first sample program uses loops and arrays to calculate the first twenty Fibonacci numbers. Fibonacci numbers are used to determine the sample points used in certain optimization methods.
/* Program to calculate the first 20 Fibonacci numbers. */
#include <stdlib.h>
#include <stdio.h>
int main( void ) {
int i, fibonacci[ 20 ];
fibonacci[ 0 ] = 0;
fibonacci[ 1 ] = 1;
for( i = 2; i < 20; i++ )
fibonacci[ i ] = fibonacci[ i - 2 ] + fibonacci[ i - 1 ];
for( i = 0; i < 20; i++ )
printf( "Fibonacci[ %d ] = %f\n", i, fibonacci[ i ] );
} /* End of sample program to calculate Fibonacci numbers */
Exercise: What is the output of the following program:
/* Sample Program Using Arrays */
#include <stdlib.h>
#include <stdio.h>
int main( void ) {
int numbers[ 10 ];
int i, index = 2;
for( i = 0; i < 10; i++ )
numbers[ i ] = i * 10;
numbers[ 8 ] = 25;
numbers[ 5 ] = numbers[ 9 ] / 3;
numbers[ 4 ] += numbers[ 2 ] / numbers[ 1 ];
numbers[ index ] = 5;
++numbers[ index ];
numbers[ numbers[ index++ ] ] = 100;
numbers[ index ] = numbers[ numbers[ index + 1 ] / 7 ]--;
for( index = 0; index < 10; index++ )
printf( "numbers[ %d ] = %d\n" index, numbers[ index ] );
} /* End of second sample program */