arraysccharprintfconversion-specifier

Why are there garbled characters in this C program output?


#include <stdio.h>
#include <locale.h>
#include <wchar.h>

int main() {
//    setlocale("LC_ALL","");
    unsigned char utf[]={0xe4,0xb8,0x80,0x0a};
    printf("%s",utf);
    return 0;
}

enter image description here


Solution

  • Your array is missing the null terminator strings require, so printf keeps on printing bytes beyond the end of the array until it happens upon a null byte. (Or when your program crashes due to an out of bounds access.)

    Add the null byte:

    unsigned char utf[]={0xe4,0xb8,0x80,0x0a,0x00};