6.5. Arrays and Pointers

Integers and floating-point variables are useful to be sure, but what do you do if you need to represent lots of numbers of the same type? Coming up with unique variable names for each one could be quite tiresome. Take the following code, for example:

int var0 = 1;
int var1 = 5;
int var2 = 3;
int var3 = 2;
int var9 = 7;

If you had to make up variable names to represent a thousand values like this, you would soon lose any interest you might have had in writing C programs.

Luckily, C provides array variables, which are variables containing many values of the same data type. If you consider the preceding code, you will notice that each variable name starts with var and has a number appended to make it unique. Arrays work the same way, except the number, or index, is not part of the variable's name. Here is an example similar to the preceding code, but using an array instead of multiple simple variables:

int var[10];
var[0] = 1;
var[1] = 5;
var[2] = 3;
var[3] = 2;
var[9] = 7;

The array variable var contains 10 integers. You can see that from the way it has been declared: the number 10 in square brackets is the size of the array. The indexes are used to access the elements of the array range between 0 and 9, and appear in the square brackets directly after the variable name. Array indexes in C always begin at 0; this differs from some other programming languages that begin counting at 1.

If the preceding examples have you wondering what the advantage ...

Get Beginning Mac OS® X Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.