简体   繁体   中英

Initialize wide char array

I have a wide char variable which I want to initialize with a size of string. I tried following but didn't worked.

std::string s = "aaaaaaaaaaaaaaaaaaaaa"; //this could be any length 
const int Strl = s.length();
wchar_t wStr[Strl ]; // This throws error message as constant expression expected.

what option do i have to achieve this? will malloc work in this case?

Since this is C++, use new instead of malloc .

It doesn't work because C++ doesn't support VLA's. (variable-length arrays)

The size of the array must be a compile-time constant.

 wchar_t* wStr = new wchar_t[Strl];

 //free the memory
 delete[] wStr;

First of all, you can't just copy a string to a wide character array - everything is going to go berserk on you.

A std::string is built with char , a std::wstring is built with wchar_t . Copying a string to a wchar_t[] is not going to work - you'll get gibberish back. Read up on UTF8 and UTF16 for more info.

That said, as Luchian says, VLAs can't be done in C++ and his heap allocation will do the trick.

However, I must ask why are you doing this? If you're using std::string you shouldn't (almost) ever need to use a character array. I assume you're trying to pass the string to a function that takes a character array/pointer as a parameter - do you know about the .c_str() function of a string that will return a pointer to the contents?

std::wstring ws;
ws.resize(s.length());

this will give you a wchar_t container that will serve the purpose , and be conceptually a variable length container. And try to stay away from C style arrays in C++ as much as possible, the standard containers fit the bill in every circumstance, including interfacing with C api libraries. If you need to convert your string from char to wchar_t , c++11 introduced some string conversion functions to convert from wchar_t to char, but Im not sure if they work the other way around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM