Reputation: 1
My teacher keeps starting arrays from 1 by starting the array with (myarray[n+1]
) and inputting from i=1
and up.
Is this common practice in the real world? He has been doing some other weird stuff but this is the one that has me fumbled.
Upvotes: 0
Views: 100
Reputation: 2767
The C/C++ way is to use array index starting with 0. For an in depth discussion look at Andrew Koenigs excelent series about asymetric bounds. Part1, Part2, Part3, Part4 and Part5. But there are some algorithm which are easier to describe when arrays start with 0. One is heapsort.
Upvotes: 0
Reputation: 110658
No, this is not a common practice. It's normally considered bad practice.
Index arrays in the way that the language is designed to. If you really want to index from 1, use Matlab. It might be useful for you to ask your teacher why they do it (and then tell them not to).
An arrays elements are always initialized in some way or another. Even if you simply ignore the 0th element, it's still there and it's wasting memory unnecessarily. Its constructor could even potentially have some unwanted side effects.
You're also going have lots of pains when you want it to play nice with the standard library. Suddenly you have to think carefully when you create a vector with std::vector<int> v(array, array+N)
or std::vector<int> v(std::begin(array), std::end(array))
. Similarly with the standard algorithms and such.
If you want a reason to feel comfortable with indexing from 0, remember that it's merely an offset. The array subscript operator a[i]
is equivalent to *(a + i)
. It basically just offsets the pointer a
(retrieved perhaps through some conversion) by i
.
Upvotes: 5
Reputation: 129374
I have been programming in C and C++ for a living for the past 20 or so years, and never ONCE seen this in any code that I've worked on. So, no, it's definitely not something that is common, or even recommended. Which is the same as what everyone else is saying...
Upvotes: 0
Reputation: 5525
Not in C++, as in C++ the index represents offset from the beginning of memory block allocated for the array. So in fact, your teacher is wasting certain numer of bytes (depending of what the array comprises).
It's used, for instance, in Lua, where arrays typically start at 1.
Upvotes: 1
Reputation: 55887
No of course. Arrays in C++ starts from 0 and it's common. And more, you pay for one-more unneeded element, that is not good in real world.
Upvotes: 2