printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

前端 未结 6 2034
自闭症患者
自闭症患者 2020-12-02 23:29

I have tried the following code:

wprintf(L\"1 %s\\n\",\"some string\"); //Good
wprintf(L\"2 %s\\n\",L\"some string\"); //Not good -> print only first char         


        
6条回答
  •  难免孤独
    2020-12-02 23:54

    The format specifers matter: "%s" says that the next string is a narrow string ("ascii" and typically 8 bits per character). "%S" means wide char string. Mixing the two will give "undefined behaviour", which includes printing garbage, just one character or nothing.

    One character is printed because wide chars are, for example, 16 bits wide, and the first byte is non-zero, followed by a zero byte -> end of string in narrow strings. This depends on byte-order, in a "big endian" machine, you'd get no string at all, because the first byte is zero, and the next byte contains a non-zero value.

提交回复
热议问题