Search code examples
cstringmatrixprintingputs

Printing a matrix without for loops


I'm trying to print a char matrix using a single puts instead of nested loops, but I always get one more character in the end of the printing. I'm going to make a pong game, and I need to update the screen as fast as possible.

void main()
{
    int x, y;
    char map[40][80];

    for(y=0; y<40; y++)
    {
        for(x=0; x<80; x++)
        {
            map[y][x]='o';    //Just for testing.
        }
    }
    puts(map);
}

The last two lines printed with this code are:

ooooooooooooo...o (80 'o's)
<

Solution

  • #include <stdio.h>
    
    int main(int argc, char **argv)
    {
        int x, y;
        char map[40*80+1];
    
        for(y=0; y<40; y++) {
            for(x=0; x<80; x++) {
                map[y*80+x]='o';
            }
        }
        map[40*80] = '\0';
        puts(map);
    
        return 0;
    }
    

    I've change the map to a linear array. This way it's easier to add a \0 at the end to close the string. Without the \0, the puts() command doesn't know when to stop printing. In your case it was just a <, but it could have resulted in printing a lot of characters!

    Also, I wouldn't rely on the fact that a multi-dimensional array maps linearly in memory.