Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method is correct for Initializing a wchar_t string?

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.

like image 908
Neon Flash Avatar asked Apr 11 '13 14:04

Neon Flash


2 Answers

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.

like image 71
alk Avatar answered Oct 10 '22 08:10

alk


It really depends on what you want to do and how you use the data. If you need it globally, by all means, define a static array. If you only need it in a method, do the same in the method. If you want to pass the data around between functions, over a longer lifetime, malloc the memory and use that.

However, your method III is wrong - it is an array of 100 wchar_t pointers. If you want to create a 100 large wchar_t array and a pointer, you need to use:

wchar_t message[100], *message_pointer;

Also, concerning terminology: you are only declaring a variable in the method I, you never assign anything to it.

like image 25
Femaref Avatar answered Oct 10 '22 07:10

Femaref