You'll need two reference variables as well.
- Code: Select all
i = 3; // max 5
j = 2; // never more than 3
Grid[i][j] = 345;
The problem with this approach, especially with a screen sized array is that you have to make sure you dont/cant address cells outside the array, or you get a nasty error. You end up with a whole bunch of if statements, which is the original reason I put that quote in my sig.
So a more clever way to approach that is to use a 1D array and calculate your 2D location when you access it.
to get a 2D location in a 1D array, consider that you'll need to keep a record(variable) of how big the x size really is. In our case, i can be no greater than 5, right? So MaxGridX = 5.
Now we just have to multiply MaxGridX by current j to get our location vertically. then we add our offset, which is variable i in this case. I'll code it up..
- Code: Select all
int Grid[5*3]; // yeah you can do this to remind yourself, otherwise use 15
int MaxGridX = 5;
int i = 3;
int j = 2;
Grid[i+MaxGridX*j] = 345;
Thats how that works. Now we only have to have if statements to make sure that we dont fall out of the top and bottom of the array. The sides are protected. You only have to use
- Code: Select all
if((i+MaxGridX*j) < 0)
{ // problem solving code here} // our number is too small
if((i+MaxGridX*j) > (sizeof(Grid)))
{ // problem solving code here} // our number is too big
Which is much shorter.
But I will give you a tip. There is a way to eliminate and shorten those as well. Can you figure it out?