Public Group

Stupid L"" and WCHAR question

This topic is 4749 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi, man I feel stupid asking a simple question like this. But I can't figure it out. If I do this it works fine: WCHAR wcTest[1] = L""; But when I do this: WCHAR wcTest[1]; wcTest = L""; or WCHAR wcTest[1]; wcTest[1] = L""; I get a conversion error on VC++ 6. Why does this not work and can someone show me the correct way. Thanks Talib

Share on other sites
WCHAR wcTest[1] = L""; declares a WCHAR array with one element. Since you can initialize char and wchar arrays with strings, this works.

In the second example you declare a one element WCHAR array, then you try to assign a string to it. Since strings are essentially pointers, you can't do this other than at initialization. In fact, you can't do someArray = someVariable at all, since it would have no meaning. What is to be assigned? The first element? All elements?

In the third example, you once again declare the one element array and then try to assign the string L"" (which, as I previously pointed out, is in fact a pointer) to the second element of the one element array (remember, arrays start counting from 0). Since wcTest[1] is a WCHAR array, you can only assign other WCHARs to it without an explicit conversion. Additionally, when writing to the second element of a one element array you're overstepping the array's bounds, which is pretty likely to overwrite other variables.

Now, to copy a string into a WCHAR array after the array has been declared you'd use wcsncpy (or perhaps wstrncpy with MSVC6):
const int ARRAY_LENGTH = 20;WCHAR wcTest[ARRAY_LENGTH]; // Declare a WCHAR array big enough to hold our stringwcsncpy(wcTest, L"Hello WCHAR!", ARRAY_LENGTH); // Copy "Hello WCHAR!" to wcTest, making sure we don't overwrite the array bounds by accident

EDIT: I fail at text formatting.

Share on other sites
Thanks

I remember reading stuff about arrays being pointers etc somewhere. I guess the info didn't stick.

1. 1
2. 2
3. 3
Rutin
18
4. 4
JoeJ
14
5. 5

• 14
• 10
• 23
• 9
• 32
• Forum Statistics

• Total Topics
632630
• Total Posts
3007525
• Who's Online (See full list)

There are no registered users currently online

×