C23
C23

Reputation: 11

Fast Output of 2D Array C

I'm looking to use a method of outputting a 2D array that is optimized for speed. currently I'm using:

for (int row(0); row < 20; ++row)
    {
        for (int col(0); col < 30; ++col)
        {
            putchar(grid[row][col]);
        }
        putchar('\n');
    }

this works fine however after testing a few things I noticed that using

printf("%s", grid);

I received a massive speed boost, however this was formatted incorrectly as it just output a long string of chars for my array rather than the 30x20 grid I want. I'm wondering if there is any method to get the speed shown with the printf line that formats the grid correctly.

For reference I get about 33ms when using the first method and 1.5ms with the second method.

Upvotes: 0

Views: 302

Answers (2)

Barmar
Barmar

Reputation: 780655

You can write each row at once using fwrite():

for (int row = 0; row < 20; ++row) {
    fwrite(grid[row], sizeof grid[row], 1, stdout);
    putchar('\n');
}

BTW, your code that writes the whole grid using printf("%s", grid) is most likely causing undefined behavior. %s requires the argument to be a pointer to a null-terminated string, and grid presumably doesn't have a null at the end. If it seems to be working it's just accidental, because there happened to be a null byte in the memory following grid.

Note that this solution only works for an actual 2-D array of char. If it's an array of pointers, you can replace sizeof grid[row] with a variable or macro that specifies the size of each row pointed to by grid[row] (or just a hard--coded 30 as in the question).

Upvotes: 4

nikau6
nikau6

Reputation: 961

if you make each of you lines terminate with a '\0' char, you can do that :

for(int row=0; row<20; ++row)
{
    printf("%s\n", grid[row]);
}

Upvotes: 2

Related Questions