Array Terminology – What Is the Difference Between an Index and an Offset?

arrayterminology

I am looking to understand the difference between the words index and offset.
I have never seen "offset" in reference to lists/arrays/etc in programming. I have only seen index.

To me, these mean the same thing. But how one is used heavily and one never implies they have different meanings. They might also just have historical or mathematical significance I'm not seeing.

Using the code snippet as a reference:

x = arr[0];
y = arr[2];

all the below statements are true:

  • x has an index of zero
  • x is offset from the beginning of the array by zero
  • y has an index of 2
  • y is offset from the beginning of the array by 2

This really makes it look like index and offset mean the same thing.

Best Answer

An index stands alone, though some data structure (e.g. array) is implied in using the index.  Still the index can be used (e.g. as an id) without an array.

An offset has to be an offset from something, so the difference is in the degree with which another entity is implied.  s[105] is offset by 5 from s[100] (e.g. we may have a substring at 100-105).  Here the value 5 does not really stand alone, whereas indexes 100 and 105 do stand alone (to a larger degree, at least).


Index is often used with arrays whose element size is fixed, and indexes are implicitly scaled by that size constant (in most languages but not assembly) to access an array element.

Offset is often used with variable sized items, e.g. fields at different offsets from the beginning of a struct, record or class object.  Because fields are each potentially of different size, we would not index (scale by some fixed size) into a struct to get different fields, but we would "offset" from the beginning of the struct to get a particular field.