Can't get wchar_t* from wstring

795 views Asked by At

I try to change value of wchar_t* variable with function call.

I use pointers (Changing an array with a function in C?) and when assign char* to char* or wchar_t* to wchar_t* it works fine. But if I try to get wstring value and assign it to wchar_t* variable function call yields garbage/nothing.

I try to convert from wstring how it was discussed in How to convert wstring to wchar_t*? C++, Convert std::wstring to WCHAR* and std::wstring to wchar_t *.

Code example:

#include <xstring>

void newval(wchar_t **w0, wchar_t **w1, wchar_t **w2, wchar_t **w3, const wchar_t **w4) {
    //wchar_t* to wchar_t* works fine
    *w0 = L"new wchar";

    std::wstring ws = L"new wstring";
    *w1 = &ws[0];
    *w2 = const_cast<wchar_t*>(ws.c_str());
    //just in case
    *w3 = (wchar_t*)ws.c_str();
    *w4 = ws.c_str();
}

void main() {
    wchar_t *v0 = L"";
    wchar_t *v1 = L"";
    wchar_t *v2 = L"";
    wchar_t *v3 = L"";
    const wchar_t *v4 = L"";

    newval(&v0, &v1, &v2, &v3, &v4);

    fprintf(stdout, "New wchar_t: %ws", v0);
    fprintf(stdout, "\nNew wchar_t from &wstring[0]: %ws", v1);
    fprintf(stdout, "\nNew wchar_t from const_cast<wchar_t*>(wstring.c_str()): %ws", v2);
    fprintf(stdout, "\nNew wchar_t from (wchar_t*)ws.c_str(): %ws", v3);
    fprintf(stdout, "\nNew wchar_t from wstring.c_str(): %ws", v4);
}

Output:

New wchar_t: new wchar  
New wchar_t from &wstring[0]:  
New wchar_t from const_cast<wchar_t*>(wstring.c_str()):  
New wchar_t from (wchar_t*)ws.c_str():  
New wchar_t from wstring.c_str():  

What's wrong with my code and how I can change wchar_t* variable using wstring value?

P.S. I can't submit question if output isn't formatted as code.

0

There are 0 answers