Spurious blank generated in simple Win32 Console app

RichardOnRails2 ha scritto:
> Hi,
>
> I'm a rusty C++ programmer trying to help a new-comer to write a
> permutations-generator. In my first dozen lines of so manage to write
> an unexpected blank character.
>
> The program and its output are posted at http://www.pastie.org/291679.
>
> The third line " PQR" should be simply "PQR" IMHO. I've made some
> dumb mistake. Learning where it is would be most appreciated.
>

Assuming you work on a platform where the size of pointers is four
bytes, the expression "sizeof(s)/sizeof(*s)" in line 6 always evaluate
at compile time to 4, regardless of the content of the string pointed by
s. In fact sizeof(s) is the size of *the pointer*, which is always four,
and sizeof(*s) is the size of a character, which is always one. As you
use "sizeof(s)/sizeof(*s)" as the size of the field "%*s" you are
actually requesting the blank of padding you see.

Notice the expression "sizeof(a)/sizeof(*a)" in line 13 is a completely
different case, that unfortunately is also wrong. In fact a is an array
(not a pointer as in the previous case) so the result is the number of
elements of the array, which unfortunately is also 4 and not 3, because
of the implicitly added terminating '\0'.

Remember: sizeof returns size of a type or object, NOT the length of a
string (be it a literal or not).

BTW, why did you write:

printf("%*s\n", sizeof(s)/sizeof(*s), s);

where you probably just meant:

printf("%s\n", s);

or, even better:

std::cout << s << '\n';

HTH,

Ganesh

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google