1

I need to convert from char* to wchar. Here is how i am doing.

char * retrunValue= getData();
size_t origsize = strlen(returnValue) + 1;
const size_t newsize = 200;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, returnValue, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");

getData() function returns a char* value for example "C:/Documents and Settings" when i tried to print the converted value "wcstring": the value is not correct: it is something like this "C:/Documen9" or something garbage. 1- Please tell me is it safe to convert from char* to wchar in this way, as i am doing 2- How can i get the original value as returned by getData() function

Thanks, Regards

UPDATE:

size_t origsize = strlen(returnValue) + 1;
const size_t newsize = 200;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
wsprintf(wcstring, newsize, L"%S (wchar_t *)", returnValue);

added this but it says. "argument of type "size_t is incompatible with parameter of type "LPCWSTR" "

Asghar
  • 2,336
  • 8
  • 46
  • 79

2 Answers2

5
mbstowcs_s(&convertedChars, wcstring, newsize, returnValue, _TRUNCATE);
                                      ^^^

You're passing the wrong size.

Erik
  • 88,732
  • 13
  • 198
  • 189
  • Thanks i tried. wcstring value is 0x023bf9e8 "C:\DocumÈ (wchar_t *)" and returnvalue is 0x023bf890 "ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ. While my original value c:/documents and settings. i dnt know why my returned value is wrong. – Asghar May 07 '11 at 10:04
3

Don't use mbstowcs() for such conversions unless the char* really points to a multibyte string (not every char string is a multibyte string!). It might break when using char values above 127 (e.g. umlauts and other special characters).

As you'd like to concat another string anyway, just use wsprintf():

// Visual Studio
wsprintf(wcstring, newsize, L"%S (wchar_t *)", returnValue);

// GCC
wsprintf(wcstring, newsize, L"%ls (wchar_t *)", returnValue);
Mario
  • 35,726
  • 5
  • 62
  • 78