Categories

Programmers who come to C from another language frequently get confused when C treats an array as an address and vice versa. After all, isn’t an array supposed to be some sort of container with a fixed number of slots, each of which holds a single item? An address is just a number indicating a memory location; so an array and an address are very different things, right?

Well, no, not right, as it turns out.

C is correct: an array is just the base address of a block of memory, and the array notation you may have come across when learning a language, such as Java or JavaScript, is merely syntactic sugar.
Look carefully at the following code:

```static int _x;

int i;

for (i = 0; i < 4; i++) {
_x[i] = (int) (_x + i);
}

for (i = 0; i < 4; i++) {
printf("%x:%x:%x\n", _x + i, _x[i], *(_x + i));
}

}
```

Here, the first for loop copies the address of each individual array element into the array itself:

```_x[i] = (int) (_x + i);
```

At each turn through the loop, the address is incremented by the value of i. So the address of the array variable _x will be the first element (since i is 0 at the first turn through the loop), and each subsequent address will be the address of _x plus 1. When we add 1 to the array’s address, the C compiler calculates the appropriate offset to the next array element according to the data-type of the array (here, that’s 4 bytes for an array of integers).

The second for loop prints the values stored in the array, first printing the address of the element _x + i, then the value of the element using normal array indexing _x[i], and finally the contents of the array using pointer/address notation (where the * operator returns the contents of the address placed in parentheses): *(_x + i). In all cases, the three values are the same. This shows that the array and its address are the same thing, and each element in the array has an address given by the address of the array, plus the number of bytes needed to store an element.

Incidentally, note that you don’t need to use the & operator to get the address of the array, because, to the compiler, the array is an address.