Reputation: 129
My teacher usually starts indexing arrays from one. So, basically, when we need an array of 100 elements he uses
int a[101]
instead of
int a[100]
and, for example, he fills it like this:
for (int i = 1; i <= 100; i++)
cin >> a[i];
Are there any problems with using this method, or should I avoid it? (I don't have any problems in working with indexes starting from 0)
Upvotes: 4
Views: 3341
Reputation: 44248
Should I use this regularly, or should I avoid it?
You should avoid it. One problem is that 99.9% of C++ developers would not share this bad habit with you and your teacher, so you will find their code difficult to understand and vice versa. However, there is worse problem with that. Such indexing will conflict with any standard algorithm and others that follow them and you would have to write explicit pesky code to fix it as container.begin()
and container.end()
as well as std::begin()
and std::end()
for C style arrays to work with accordance to the C++ standard which is 0 based.
Note: As mentioned in comments for range loop, which is implicitly using begin()/end()
would be broken as well for the same reason. Though this issue is even worse as range used implicitly and there is no simple way to make for range loop work in this case.
Upvotes: 17
Reputation: 3233
The size of an int
is really compiler dependent. Back in the days when processors used to be 16 bit, an int
was 2 bytes. Nowadays, it's most often 4 bytes on a 32-bit as well as 64-bit systems.
The best way of checking size of int
is
cout << sizeof(int);
When you declare a statement
int array[10];
You tell Compiler to reserve 40 BYTES for use(based on Assumption above.)
You are using only 9 elements (1-9) thats 36 bytes of 40 allocated wasting 4 bytes of memory. Just memory is cheap doesn't mean its free. Morever if your working with 3 dimensional arrays.
Example:
int array[100][100][100]
You will end up losing a lot of memory I mean lot of memory that other process require but can't use just because you have deliberately reserved it and not used.
If you are working with character arrays, you may something land up in disaster.
Example:
char str[8];
str[1] = 'H';
str[2] = 'e';
str[3] = 'l';
str[4] = 'l';
str[5] = 'o';
str[6] = '\0';
cout<<str;
There maybe situation where no output will be displayed as the str[0]
may contain the NULL
character.
Upvotes: -1
Reputation: 15501
Arrays in C++ and C are zero indexed, meaning the first array element is numbered with 0
and the last element is numbered with N-1
when accessed via subscript operator[]. As-is your code skips the first array element that is the a[0]
and starts off with a second element that is the a[1]
so you should avoid that practice.
Upvotes: 2