1. | Welcome | ToC | FAQ | Resources | Courses | Projects | Mail Lists | Members | Misc |
2. | Fundamentals | Languages | Tools | Net | Core | Advanced |
3. | EoC | Java |
4. | Lessons |
5. | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 |


Essence of C
4 - ARRAYS AND STRINGS

Single Dimension Arrays, Two- and Mutliple-Dimension Arrays, Strings, Arrays of Strings

An array is a collection of variables of the same type which are referenced by a common name. A specific element in an array is referenced by an index. The most common array in C is the string, which is simply an array of characters terminated by a null.

In C, arrays and pointers are closely related; a discussion of one usually refers to the other.

C has no bounds checking on arrays.

Single Dimension Arrays

The general form for declaring a single-dimension array is:

    type var_name[size];

In C, all arrays have zero as the index of their first element. Therefore a declaration of char p[10]; declares a ten-element array (p[0] through p[9]).

Generating a Pointer to an Array

A pointer to the first element in an array may be generated by simply specifying the array name, without any index. For example, given:

    int sample[10];

a pointer to the first element may be generated by simply using the name sample. For example, the following code fragment assigns p the address of the first element of sample:

    int *p;
    int sample[10];

    p = sample;

The address of the first element may also be specified using the & operator. For example, sample and &sample[0] produce the same result. The former is usually used.

Passing Single-Dimension Arrays to Functions

In C, an entire array cannot be passed as an argument to a function. However, a pointer to an array may be passed by specifying the array's name without an index. If a function receives a single dimension array, the formal parameter may be declared as either a pointer, a sized array, or an unsized array. Examples are:

    function(int *x)     // A pointer.
    function(int x[10])  // A sized array.
    function(int x[])    // An unsized array.

Strings

A string is actually an array of characters. Because strings are terminated by a null ('\0'), character arrays must be declared with one extra element (to hold the null).

Although C does not have a string data type, it allows string constants. For example, "hello there" is a string constant.

C supports a wide range of string manipulation functions, including:

Function Description
strcpy(s1,s2) Copies s2 into s1.
strcat(s1,s2) Concatenates s2 to s1.
strlen(s1) Returns the length of s1.
strcmp(s1,s2) Returns 0 (false) if s1 and s2 are the same.
Returns less than 0 if s1&lts2
Returns greater than 0 if s1>s2
strchr(s1,ch) Returns pointer to first occurrence ch in s1.
strstr(s1,s2) Returns pointer to first occurrence s2 in s1.

Since strcmp() returns false if the strings are equal, it is best to use the ! operator to reverse the condition if the test is for equality.

Two-Dimensional Arrays

In C, a two-dimensional array is declared as shown in the following example:

    int d[10][20];

Two-dimensional arrays are stored in a row-column matrix. The first index indicates the row. The row index can be thought of as a &quotpointer"to the correct row.

When a two-dimensional array is used as an argument to a function, only a pointer to the first element is passed. However, the receiving function must define at least the length of the second dimension, e.g.:

    function(int x[][20]

Arrays of Strings

Arrays of strings are created using a two-dimensional array. The left index determines the number of strings. Each string is accessed using only the left index (eg, gets(array[2] accesses the third string).

Multi-Dimensional Arrays

C allows arrays of more than two dimensions, the exact limit depending on the individual compiler.

Indexing Pointers

In C, pointers and arrays are closely related. As previously stated, an array name without an index is a pointer to the first element. For example, given the array char my_array[10];, my_array and &my_array[0] are identical.

Conversely, any pointer variable may be indexed as if it were declared as an array. For example, in this program fragment:

    int *p, i[10];

    p = i;
    p[5] = 100;	// assignment using index
    (p+5) = 100	// assignment using pointer arithmetic

both assignments achieve the same thing.

Pointers are sometimes used to access arrays because pointer arithmetic is faster than array indexing.

In a sense, a two-dimensional array is like an array of pointers that point to arrays of rows. Therefore, using a separate pointer variable is one easy way to access elements. For example, the following prints the contents of the specified row for the global array num:

    int num[10][10];
    ...
    void print_row(int j)
    {
      int *p, t;

      p = &num[j][0]; // get address of first element in row j
      for(t=0;t<10;++t)
        printf("%d ", *(p+t));
    }

Array Initialization

Arrays may be initialized at the time of declaration. The following example initializes a ten-element integer array:

    int i[10] = { 1,2,3,4,5,6,7,8,9,10 };

Character arrays which hold strings allow a shorthand initialization, e.g.:

    char str[9] = "I like C";

which is the same as:

    char str[9] = { 'I',' ','l','i','k','e',' ','C','\0' };

When the string constant method is used, the compiler automatically supplies the null terminator.

Multi-dimensional arrays are initialized in the same way as single-dimension arrays, e.g.:

    int sgrs[6][2] =
    {
      1,1,
      2,4,
      3,9,
      4,16,
      5,25
      6,36
    };

Unsized Array Initializations

If unsized arrays are declared, the C compiler automatically creates an array big enough to hold all the initializers. This is called an unsized array. Example declaration/initializations are as follows:

    char e1[] = "read error\n";
    char e2[] = "write error\n";

    int sgrs[][2] = 
    { 
      1,1,
      2,4,
      3,9
      4,16,
    };

Prior Chapter · Index · Next Chapter


Copyright © 1996, 1997, 1998. Last Update to This Page: 1998/10/24
This Page Maintained by: radar pangaean * * * Original Author: K.J.Bricknell
The MOST web site is built and maintained by the voluntary efforts/donations of our members.