Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a wchar_t variable?

I am reading the book: C: In a Nutshell, and after reading the section Character Sets, which talks about wide characters, I wrote this program:

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

int main() {
  wchar_t wc = '\x3b1';
  wprintf(L"%lc\n", wc);
  return 0;
}

I then compiled it using gcc, but gcc gave me this warning:

main.c:7:15: warning: hex escape sequence out of range [enabled by default]

And the program does not output the character α (whose unicode is U+03B1), which is what I wanted it to do.

How do I change the program to print the character α?

like image 891
Yishu Fang Avatar asked Oct 21 '12 08:10

Yishu Fang


People also ask

How do you initialize a Wchar string?

This method of initializing a string works good for me. Method II: wchar_t *message; message=(wchar_t *) malloc(sizeof(wchar_t) * 100); This method will first initialize the variable message as a pointer to wchar_t .

What does wchar_t mean in C?

The wchar_t type is an implementation-defined wide character type. In the Microsoft compiler, it represents a 16-bit wide character used to store Unicode encoded as UTF-16LE, the native character type on Windows operating systems.

What is the default value of array data type wchar_t?

The default value for wchar_t is zero so there's no need to even give any values in the brackets.

How many bytes is Wchar?

wchar_t is 2 bytes (UTF16) in Windows.


2 Answers

This works for me

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

int main(void) {
  wchar_t wc = L'\x3b1';

  setlocale(LC_ALL, "en_US.UTF-8");
  wprintf(L"%lc\n", wc);
  return 0;
}
like image 167
David Ranieri Avatar answered Oct 02 '22 22:10

David Ranieri


wchar_t wc = L'\x3b1';

is the correct way to initialise a wchar_t variable to U+03B1. The L prefix is used to specify a wchar_t literal. Your code defines a char literal and that's why the compiler is warning.

The fact that you don't see the desired character when printing is down to your local environment's console settings.

like image 25
David Heffernan Avatar answered Oct 03 '22 00:10

David Heffernan