Skip to main content

2.6 Arrays

An array in C is a data structure that is used to store a collection of same-type objects. The syntax for declaring, say, an integer array is:

int g[100];

You have already encountered the idea of a character array when using strings.

The element count in an array in C always starts off from zero, so in the example above, the first element of this array is located in count[0], and the last element is located in count[99]. Example of usage of multiplication of a scalar by a vector is given in the code fragment below:

double g[]={1.0, 2.0 ,3.0};
double a=5.0;
int index;

for (index = 0; index < 3; index++) {
    g[index] *= a;
    printf("element %d is now %f \n",index,g[index]);
}

WARNING: You should always be careful to not address elements that are outside your delclared array - in the above example this would be like trying to access g[3]. If you tried to write something to g[3] in this example, it would be written to random memory - and that can cause unpredicatable things to happen! (usually your program will crash but not always). Note that if you make an error like this in your code, the compiler will not pick it up - so be careful!

Multidimensional arrays are possible in C. For example, to store a matrix in C, you can declare a two-dimensional array, e.g., below is a declaration for a 3 by 3 matrix:

float M[3][3]

Since memory is linearly addressable, matrices in C in stored are in row-major order , as depicted below.

Arrays will come up again, when you read about pointers.