0

I wrote this function that writes a 2D vector to stdio using printf()

static void printSheet ( const storage::twoDVec& Sheet, char format='g'
                       , char elDelim='\t', char vecDelim='\n') 

    const size_t vecSize = Sheet.vecSize;
    const size_t subVecSize = Sheet.subVecSize;
    char pFormat[3] = {'%', format, elDelim};
    for ( size_t y = 0; y < vecSize; y++ ) {
        for ( size_t x = 0; x < subVecSize; x++ ) {
            printf(pFormat, Sheet.get( y, x ));
        }
    putchar(vecDelim);
    }
}

It works great unless subVecSize in [10, 13], then the format is not

x x x
x x x
x x x

For subVecSize = 10

1
2
...
9
10

1
2
...
9
10

(Repeating). For 11 and 12 the subVectors scroll across diagonally and for 13 the subvectors overwrite themselves. eg if vecSize==1 && subVecSize==3 then I only get one number as an output.

Am I over looking something or do I not understand something fundamental about printf()? Changing elDelim to ' ' doesn't change it.

4

1 回答 1

5

Your pFormat array is not null terminated. Try this

char pFormat[4] = {'%', format, elDelim, '\0'};
于 2013-09-28T22:39:15.237 回答