I'm not sure whats going on here. I can't get my head around it but the if loop doesn't seem to like looping more than 8 times >.<
I have a simple program that i want to use to draw a block of characters on the terminal. First it initializes a multi-dimensional array, 1 dimension for x, 1 for y. Next it goes through an if loop to assign the char # to each part of the array. But in this loop somewhere something goes wrong because wall[8][9] and wall[9][0] both end up equaling '?' and wall[9][1] - wall[9][9] equal ''. :S
I'm very confused. Anyway here is the code:
There is nothing wrong with using the <= but you must realize that it is inclusive with 9. That means the for loop is going from 0 to 9, which is 10 times. Your array only has 9 slots in it.
The solution is to either, like you realized, increase the size of your array to 10, or to change the for loop so it goes from 0 to 8 (nine times). You could do this either by using a < instead, or changing the expression to a <= 8.
The solution is to either, like you realized, increase the size of your array to 10...
What kind of a solution is that? I need an array with nine elements in it, so I best make it ten because I'm not going to work within the bounds correctly.
You can, technically, use <= in a for loop. However, when working with arrays inside the the loop it is easier an less error prone to just use <.
int main()
{
enum {arraySize = 9}; // or some other constant inegral
int anIntArray[ arraySize ];
int i(0);
for (i = 0; i < arraySize; ++i)
{
anIntArray[i] = i;
}
// The following dose the same
for (i = 0; i <= arraySize - 1; ++i)
{
anIntArray[i] = i;
}
return 0;
}
Initialising an array of size 10? Thats why i thought <= should work. I will try just using < from now on in if statements to see if that works. Thanks for the replies guys :)
Nope. The number doesn't represent the highest index but the total number of elements (the size). So if you want 10 elements, you must use int array[10];.