+ 3
Array subscript values are always integer...!!why?
2 Answers
+ 4
Array indexes are always integers, because at the lowest level, arrays are contiguous blocks of memory, and the array is simply represented by a pointer to its first element.
The program has to perform numeric addition to this pointer to retrieve the successive element from the allocated memory.
Eg :
When you do :
int a[5]; a[2]=3; printf("%d",a[2]);
or
int[] a=new int[5]; a[2]=3; System.out.print(a[2]);
The a[2] is translated into *(a+2), where a is the first element.
Thus, if the index is non-integer, it cannot be used to retrieve from memory.
But if you wish to retrieve something like this:
a['c']; // c is the 3rd element, not the 99th
you may use Map, which maps the element with a unique key, which can then be used to retrieve an element. The implementation at the lowest level, however still uses integers to retrieve the data.