Back to A Brief Guide to C


An array is a list of data, held in memory, that is accessible by naming the variable it is associated with and the item's "number." THe technical way to think about them: Think of the array as a pointer to the address in memory of the head of the array, and the number in brackets the offset, in bytes, from the head of the array divided by the size of the data type. So in a system with 1-bit chars, and an array of type char named foo, the statement foo[5] would look at foo's base address, then count 5 * 1 bytes through memory, and return the value at that address.

Arrays are used for almost every non-trivial program in C. Here's how to define & use them:
   int main() {
01     int a[15]   /* an integer array with 15 items */
           b[15],   /* another */
03         c[5][5], /* a 2-dimensional array */
           i, j;    /* a couple 'normal' integers */
       /* define & set initial values like this: */
06     char foo[5] = {'a', 'b', 'c', 'd', 'e'};
        
08     for (i = 0; i < 15; i++)
           a[i] = b[15 - i] = i;
      
10     for (i = 0; i < 15; i++) {
           for (j = 0; j < 15; j++)
               c[i][j] = 0;
       }
       
       i = 5;
16     j = c[3][2] * b[0] * i; 
       /* note that the array's values start at index '0' */
   }
  • line 01: Defining a array. Simply do it like you would a normal variable, but tack on the brackets & the number of items you'd like to have in the array.
  • line 03: 2 dimensional arrays are defined by adding another bracketed number. You can have as many dimensions as you'd like -- they just get a little hard to visualize after 4. (a cube, cut into compartments, with each compartment having different values of colors? Much beyond that, and it begins twisting my noggin.)
  • line 06: You can initialize the array with values as shown here. Multidimensional arrays can be done with sets of brackets; for instance:

    int a[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    /* or, less readably: */
    int b[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
  • lines 08 and 10: These lines show pretty simple methods for initializing arrays. Using the loops, with the counter variables set to fail at the size of the array (using <, not <=) is a pretty failsafe way to init arrays.
  • line 16: Accessing values in an array. Easy. Remember, array values start at index 0. Remember that the value in brackets is simply an offset from the head of the array, not the 'position in line' (which is the easiest way to think of it, but not really right and confusing to some people).

Log in or register to write something here or to contact authors.