Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Hi,
My code snippet looks like this.

C++
typedef char* PSTRING;

LPWSTR   usri1_name;
wchar_t  ws[100];

PSTRING createUserVar = NULL;

/*"createUserVar"  is assigned with some value*/
/*Converting PSTRING to wchar_t */
swprintf(ws, 100, L"%hs", createUserVar);


Now i need to assign ws value to usri1_name but i am not getting how to convert it.
Please let me know your suggestion on this.

different ways of doing this also welcomed.

code is written in c
Posted
Updated 27-Jul-20 14:48pm
v2

There is no need for a conversion. LPWSTR is a pointer to a wide string and ws is an array of wide characters. So you can just write:
C++
usri1_name = ws;

But you must take care of the memory pointed to by usri1_name. The pointer will become invalid when ws goes out of scope (e.g. when leaving the function or block where ws is defined). Then you must allocate memory on the heap using new or malloc for usri1_name, copy the content of ws into it, and release the memory when no longer needed.
 
Share this answer
 
Comments
Leo Chapiro 26-Jun-15 10:46am    
+5 :)
Sergey Alexandrovich Kryukov 26-Jun-15 11:02am    
5ed.
—SA
CPallini 26-Jun-15 11:32am    
5.
As WCHAR is actually wchar_t and LPCWSTR is actually wchar_t const*, you can do simple:

C++
usri1_name = ws;
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 26-Jun-15 11:03am    
5ed.
—SA
Leo Chapiro 26-Jun-15 13:37pm    
Thank you, Sergey :)
I think both of the answers miss an important point, which is that you must ensure that the character following the last character that you want to be part of the string must be NULL (0x00). Otherwise, you risk a buffer overrun when your code searches for the end of the string, and runs off the end of your 100 character array.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900