UMBC CMSC 201 Spring '02 | CSEE | 201 | 201 S'02 | lectures | news | help |
In C, an array will be implemented as a single block of memory, with element 0 occupying the first "slot" in that block. As a result, C subscripts are closely related to actual memory addresses, and to the notion of "pointer".
Possible dire consequences from the misuse of arrays should motivate you to pay close attention to the array indices.
A word is usually the amount of memory the computer uses to represent a regular integer and is also usually the smallest segment of memory that most low-level operations are designed to handle.
Typically, these are integers which begin with 0 for the first byte in memory and count upward from there.
Some data elements need more than one byte to store.
For example, an integer on an SGI computer might be encoded using four consecutive bytes and a double using eight bytes.
Such data values are indexed by the location of the first byte of their encoding.
sizeof(type) returns the number of bytes needed to represent a value of that type. sizeof x returns the number of bytes needed to store the value of the variable x.
For an array of length L and type X , the compiler allocates L*sizeof(X) bytes.
Given an array like int scores[100] , the compiler allocates 400 bytes starting at some location, say 64789.
Given an expression like scores[5] the compiler accesses the value stored at the memory location starting with byte 64789+(5*4).
In general, foo[i] is located at byte:
base address of foo + i * sizeof (type of array)
scores[9999] will try to access some random words in memory.
Making reference to elements outside of the array bounds is one of a few very common causes of sementation faults and core dumps.