0
#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;
}

  • The first four bytes of output are correct. The second line in the console is not expected

enter image description here

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

3

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};
AKX
  • 152,115
  • 15
  • 115
  • 172
1

The format %s expects a pointer to a string as the corresponding argument. That is the sequence of outputted characters shall be ended with the terminating zero character '\0'.

This array

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

does not contain a string. So you need to specify explicitly how many characters you are going to output. For example

printf("%.*s", 4, utf);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335