Home > Software design >  Why are there garbled characters in this C program output?
Why are there garbled characters in this C program output?

Time:03-28

#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

CodePudding user response:

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

CodePudding user response:

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);
  • Related