Which method is correct for Initializing a wchar_t string?

Neon Flash picture Neon Flash · Apr 11, 2013 · Viewed 36.9k times · Source

I am writing a program and I need to initialize a message buffer which will hold text. I am able to make it work, however I am writing below various ways used to initialize the strings in C and I want to understand the difference. Also, which is the most appropriate method for initializing a wchar_t/char string?

Method I:

wchar_t message[100];

based on my understanding, this will allocate a memory space of 200 bytes (I think size of wchar_t is 2 bytes on Windows OS). This memory allocation is static and it will be allocated inside the .data section of the executable at the time of compiling.

message is also a memory address itself that points to the first character of the 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. It is an array of wide characters.

next, it will dynamically allocate memory for this string. I think I have written the syntax for it correctly.

When I use this method in my program, it does not read the text after the space in a string.

Example text: "This is a message"

It will read only "This" into the variable message and no text after that.

Method III:

wchar_t *message[100];

This will define message as an array of 100 wide characters and a pointer to wchar_t. This method of initializing message works good. However, I am not sure if it is the right way. Because message in itself is pointing to the first character in the string. So, initializing it with the size, is it correct?

I wanted to understand it in more depth, the correct way of initializing a string. This same concept can be extended to a string of characters as well.

Answer

alk picture alk · Apr 11, 2013

The magic is the encoding-prefix L:

#include <wchar.h>

...

wchar_t m1[] = L"Hello World";
wchar_t m2[42] = L"Hello World";
wchar_t * pm = L"Hello World";

...

wcscat(m2, L" again");

pm = calloc(123, sizeof *pm);
wcspy(pm, L"bye");

See also the related part of the C11 Standard.