An array in C is a group of elements of the same type, where the elements are stored sequentially in memory. Square brackets are used to denote the dimension of an array:

You must declare the length of the array when it is initialized (there are ways around this but we will have to discuss pointers first).

There are many common mistakes that beginners make when getting started with arrays in C. An important concept to remember is that in C counting starts from zero. When we declare an array as:

It is obvious that there are 5 elements in the array, however a programmer must not make the mistake of trying to assign values outside the bounds of the array:

If we declare an array in C to be 5 elements, the array indices are numbered from 0 through 4. The compiler will not complain if you attempt to access an array outside its defined bounds, and you will be able to run the program. It may even work fine for a while until some other part of your code changes (thus changing the way the compiler places objects in memory). The most common error resulting from an illegal access of this kind is a segmentation fault, but you may also end up unintentionally altering the value of another variable!

Arrays can be passed to functions as an argument to the function, but a function can not return an array. Following is an example of a function that takes an array as an argument and sums up the values in that array:

 
©   Cornell University  |  Center for Advanced Computing  |  Copyright Statement  |  Inclusivity Statement