Monday, May 24, 2010

Is it possible to start numbering array cells from 1 instead of 0 in C++?

yes but it goes against convention so you need to make a note of it for others that may work on your program

Is it possible to start numbering array cells from 1 instead of 0 in C++?
The compiler will always generate internal represenations of arrays that are numbered from 0.





You can do weird tricks so your code reads as if the arrays were numbered from 1





- Ignore the zero element. In all array calculations/references you must ensure you never reference element 0


- Create an array access routine that decrements the index by 1, always use the array access routine to access arrays


- Get the source code for the Gnu C++ compiler and alter it so that all arrays are numbered by 1, and that any reference to array[0] is a fault. Compile it and post it online for everyone who wants natural numbers only.
Reply:You can use an associative array and start the keys at whatever value you wish. The trouble is you have to manage the incrementing of the keys as you add array elements.





See: http://en.wikipedia.org/wiki/Associative...
Reply:Thats a very intresting question, while I don't belive I can give you a answer that is 100% sure, because of my lack of experence in the real world, I would have to say somewhat. If you use a type of stack data structure where 0 would represent the element you are deleting and 1 as the element in which calculations are done then it would be possible. However I seriously doubt you could just start numbering arrays starting with 1 as the first index instead of 0 in any other case, because while you may not use the data in 0, unless you initaize that index there will always be something there, whatever was stored inside the memory address previously.





In any case, good luck!


No comments:

Post a Comment