An array of size N will be indexed from 0 to N-1. The standard idiomatic for loop is then like this:
for ( int i = 0; i < N; ++i )
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
>It works fine as for(i=1;i<=n;i++) .
Yes it does. But then again, so does this:
i = 9;
loopie:
// Do stuff
if ( --i > 9 - n )
goto loopie;
Most programmers prefer to use the idiomatic approach because it's easier to use, easier to get used to, and common enough that you don't have to get used to something else everytime you read a different person's program.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
It works fine as for(i=1;i<=n;i++) . Trust me. :lol:
Do you see the bug here? ;)
#include <stdio.h>
#define N 10
int main()
{
int i, array[N] = {1,2,3,4,5,6,7,8,9,10};
for ( i = 1; i <= N; ++i )
{
printf("array[%d] = %d\n", i, array[i]);
}
return 0;
}
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Hehe. :) It should be like this:
for(i=1;i<=n;i++)
NOT
for(i=1;i<=n;++i)
The second one is wrong because i increases with 1 BEFORE entering the for .. so i practically starts with the value 2. While in my example , i starts from 1 and ends at 10 , meaning exactly what it has to do. ;) :eek:
No, the second one is not wrong, and your explanation is incorrect. I take it you didn't even try it.:rolleyes:
And I take it that you still don't see the bug. This is exactly why you shouldn't be doing this.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Indeed , I haven't tested them until now. It seems like both versions give the same result ...
My guess is: i should start from 0? :p
Well, yes, but the bug is that you should not attempt to accessarray[10] because it is beyond the array bounds.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
>My guess is: i should start from 0?
If you have to guess, don't be so quick to answer questions because you'll probably be wrong. Even if you bother to test your assumptions and they pan out, you could still be wrong on something more subtle.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
char *a[5];
An array of uninitialized pointers. These are not automagically strings, you need to have them actually point to some memory you can write to before you try to write to it. Or actually declare an array for strings.
char a[5][80];
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314