Cartesian plane infinite line?

709 views Asked by At

I'm trying to make a program that makes a cartesian plane; you input the basic information of the line and it draws the line.

Too bad that it doesn't work well. Basically this is the loop that puts an X char in every point of the line:

for(int x=0;x<MAP_HEIGHT;x++)
{
    piano.griglia[x][a*x+b]='X';
}

But it does not work well! here is the result:
output

Notice how there are 3 lines where there should be only one. Here's the code of the plane, it may help:

class Cartesiano
{
public:
char griglia[MAP_LENGHT+1][MAP_HEIGHT+1];
Cartesiano( void )
{
    for(int y=0;y<=MAP_HEIGHT;y++)
    {
        for(int x=0;x<=MAP_LENGHT;x++)
        {
            if (y==0)griglia[x][y]='_';
            else
            {
                if(x==0)griglia[x][y]='|';
                else griglia[x][y]=' ';
            }
        }
    } 
}
void Draw( void )
{
    for(int y=MAP_HEIGHT;y>=0;y--)
    {
        for(int x=0;x<=MAP_LENGHT;x++)cout<<griglia[x][y];
        cout<<"\n";
    }
}
}piano;

Any ideas?

1

There are 1 answers

5
user2711915 On BEST ANSWER

When your y values exceed 49 (MAP_HEIGHT - 1) you are overflowing your array. If in your draw loop you calculate y=a*x+b and print Z instead of X you'll see the first line is X's and the overflowed errors are all Z's

for(int x=0;x<MAP_LENGTH;x++)
{
    int y = a*x+b;
    if(y<MAP_HEIGHT) {
        piano.griglia[x][y]='X';
    } else {
        piano.griglia[x][y]='Z';
    }
}

This is due to the way memory for the arrays is stored in C++, it just happens writing outside one array here causes you to write into the next one. In general doing this will crash your program.

Also note that here the x loop should be over MAP_LENGTH.

I would also strongly advise getting a proper graphics library