user8911572
user8911572

Reputation: 13

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

Upvotes: 0

Views: 382

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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

Upvotes: 1

AKX
AKX

Reputation: 168913

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

Upvotes: 3

Related Questions