3 ms·
That sounds more like a linked list than an array. In C, an array is just contiguous bytes, and you reach an index through math (starting location + (index * s
by larrik 1y ago
That sounds more like a linked list than an array.
In C, an array is just contiguous bytes, and you reach an index through math (starting location + (index * size)).
Pretty sure lots of languages still do this to some degree, as your lookup times are effectively zero, though altering the number of elements is way more complex/expensive than in a linked list.
- deepsun 1y ago> and you reach an index through math (starting location + (index * size)). By the way, that's the only reason why C-derived languages use unintuitive zero-based indexing. There's really no other reason to call the first element a[0] instead of a[1].
- dpassens 1y agoAh, but is it unintuitive though? Once one understands that in the vast majority of cases, C deals in pointers, not arrays, it makes perfect sense that indexing uses an offset rather than the nth element.
- deepsun 1y agoYes, but that's only C. Languages that have no pointer arithmetic (JavaScript, Python, Java, Rust, Go you name it) got that from C even though they didn't have to.
- tom_ 1y agoThe index of the first element is always 0 plus the index of the first element. This means it sort-of doesn't matter what the index of the first element of the array is - but, viewed another way, it's an excellent argument for 0. Starting at 0 means you don't need to add a constant in the (very common) case of dealing with a subarray that starts at the first element of the containing array.
- deepsun 1y agoYep, exactly. My point is all that is about pointer arithmetic, even though most higher-level languages don't provide you with pointer arithmetic (and their arrays may have nonzero memory offsets anyway). Pascal, Julia, R, Lua use more natural 1-based, where you call the first element first.
- tom_ 1y agoBut the first element is first whatever index you choose. Why 1, rather than, say, 99, or -3? (You should ideally be able to choose any of these options, and others - e.g., 5, 7, -200, 14,771,589,734,598,742,923,574,835, etc. - because they all make exactly as much logical sense as 1 does and any of them is as elegant a choice as 1 is. But if you get no choice, it absolutely has to be 0, because it's the only non-arbitrary option. No other number guarantees to do nothing to the value you add it to!)