Why Array Index Start from '0'

Why does array indexing in Java start with 0?

Java uses zero-based indexing because c uses zero-based indexing. C uses zero-based indexing because an array index is nothing more than a memory offset, so the first element of an array is at the memory it's already pointing to, *(array+0).

See also Wikipedia's array indexing in different languages?

Why Array index start from '0'

In most programming language, the name of any array is a pointer, which is nothing but a reference to a memory location, and so the expression array[n] points to a memory location which is n-elements away from the first element. This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array points to (0 elements away), so it should always be referred as array[0].

a[i] can also be read as value at [a+i] which is denoted as *(a+i) , so it always starts at zero.

Array indexing starting at a number not 0

Is it possible to start an array at an index not zero...I.E. you have an array a[35], of 35 elements, now I want to index at say starting 100, so the numbers would be a[100], a[101], ... a[134], is that possible?

No, you cannot do this in C. Arrays always start at zero. In C++, you could write your own class, say OffsetArray and overload the [] operator to access the underlying array while subtracting an offset from the index.

I'm attempting to generate a "memory map" for a board and I'll have one array called SRAM[10000] and another called BRAM[5000] for example, but in the "memory" visiblity they're contiguous, I.E. BRAM starts right after SRAM, so therefore if I try to point to memory location 11000 I would read it see that it's over 10000 then pass it to bram.

You could try something like this:

char memory[150000];
char *sram = &memory[0];
char *bram = &memory[100000];

Now, when you access sram[110000] you'll be accessing something that's "in bram"

Why are zero-based arrays the norm?

I don't think any of us can provide a stronger argument than Edsger W. Dijkstra's article "Why numbering should start at zero".

Should element numbering start from 0 or 1 in Java?

I think you mean

Should I call element[0] the "zeroth" element or the "first" element?

IMO, programmers often refer to it as the first element of an array. But you can also say that it is the element at index 0.

You see what I mean? In English, element[0] is always the first element. You can look up the word "first" in a dictionary to verify this. To literally "translate" element[0] into English, that would be "The element at index 0".



Related Topics



Leave a reply



Submit