Array Zing Hell

An array is a queue of values, all stored as one compact unit with a handy reference method. As you study arrays, especially when you get into pointers, you discover something interesting about the array’s first element.

Specifically, you find out that the array’s address — its location in memory — is the same as the address of the first element. For some reason this relationship causes massive confusion, maybe even convulsions.

To review, take your typical array. In this case, I’m concocting an integer array named doris, as shown in the following code:

#include <stdio.h>

int main()
{
    int doris[] = { 2, 3, 5, 8, 13 };

    printf("%p array address\n",&doris);
    printf("%p first element\n",&doris[0]);

    return(0);
}

The doris array has five elements. They’re stored in memory, one after the other, each given their own specific address and a proper number of bytes according to the sizeof an integer on whatever gizmo the code is compiled.

Lines 7 and 8 in the code display the address of doris itself (herself?) as well as the address of the array’s first element, doris[0]. Here’s the output on my computer:

0x7fff59a7fa94 array address
0x7fff59a7fa94 first element

As you can see, both addresses are the same. The start of the array itself is at memory location ...fa94 and the first element is at ...fa94. Identical.

That location makes sense to me. After all, the array starts at the first element. Why would its location be elsewhere?

What I believe is throwing some readers is that the two items being referenced are not the same. In this case, doris is an array. The compiler actually recognizes it as a memory location, a pointer. The array notation is merely window dressing. In fact, you can change Line 7 in the code to read as follows:

printf("%p array address\n",doris);

See how the & is missing before the variable doris?

The output is the same. Again, that’s because doris is really a pointer. The compiler sees the & unary operator there, shrugs its shoulders, and says “Meh.” The & is superfluous. You don’t see an error message, which may be confusing, because there is no error. Both &doris and doris are an address. The & operator doesn’t get “the address of an address” because there is no such thing.

But what about &doris[0]?

That’s a different creature: The variable doris is a pointer. The variable doris[0] is an int.

The variables doris[1], doris[2], doris[3], and doris[4] are also ints. They are not pointers. They hold integer values, not memory locations (addresses). Therefore, to fetch the address of any array element, you definitely need the & unary operator.

In the grand scheme of things, the array’s first element, doris[0] (which is an int value), is located as the same address as doris, the start of the array. Therefore, generically speaking, the memory location stored in array is always the same as the address of array[0], which is coded as &array[0].

Leave a Reply