How Are C Arrays Represented In Memory? How Are C Arrays Represented In Memory? arrays arrays

How Are C Arrays Represented In Memory?


An array is a block of contiguous objects with no spaces in between. This means that x in your second example is represented in memory as:

+---------------------+-------------+---------+| Variable Name       | Address     | Value   | +---------------------+-------------+---------+| x                   | 10568       | 12      ||                     |             +---------+|                     |             | 13      ||                     |             +---------+|                     |             | 14      ||                     |             +---------+|                     |             | ??      ||                     |             +---------+|                     |             | ??      |+---------------------+-------------+---------+

That is, x is five ints big, and has a single address.

The weird part about arrays isn't in how they're stored - it's how they're evaluated in expressions. If you use an array name somewhere that it isn't the subject of the unary & or sizeof operators, it evaluates to the address of its first member.

That is, if you just write x, you will get a value 10568 with type int *.

If, on the other hand you write &x, then the special rule doesn't apply - so the & operator works like it normally does, which means that it fetches the address of the array. In the example, this will be a value 10568 with type int (*)[5].

The reason that x == &x is that the address of the first member of an array is necessarily equal to the address of the array itself, since an array starts with its first member.


Your diagram is correct. The weirdness around &x has nothing to do with how arrays are represented in memory. It has to do with array->pointer decay. x by itself in value context decays into a pointer to its first element; i.e., it is equivalent to &x[0]. &x is a pointer to an array, and the fact that the two are numerically equal is just saying that the address of an array is numerically equal to the address of its first element.


Yes, you've got it. A C array finds the indexed value x[y] by calculating x + (y * sizeof(type)). x is the starting address of the array. y * sizeof(type) is an offset from that. x[0] produces the same address as x.

Multidimensional arrays are similarly done, so int x[y][z] is going to consume sizeof(int) * y * z memory.

Because of this you can do some stupid C pointer tricks. It also means getting the size of an array is (almost) impossible.