0

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?

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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?

5 Comments

Well, a std::string holds a char array. A wchar_t is not a char, but a wide character. He probably needs to convert a string to a UNICODE representation.
@LuchianGrigore I actually already updated my answer to reflect that. If that's what he's trying to do, manually copying the bytes over is guaranteed to fail.
Well, I hope he's not doing it with memcpy :)
@LuchianGrigore Amen to that. However, even in a loop, it'll break on the first hint of a multi-byte char. He really should be using wstring.
@MahmoudAl-Qudsi I added the links to Luchians profile and his answer. I hope you don't mind.
1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.