1

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.

Denis Osipov
  • 91
  • 1
  • 6
  • 2
    Why so much pointer usage? Using a string class should alleviate you from doing things like this, not escalate usage of pointers. Also, it's most likely garbage data, since `ws` is a local string, and you're hoping that the `c_str()` tied to it somehow is alive after the function call. – PaulMcKenzie Sep 05 '17 at 19:22
  • 3
    Your ws object is destructed after you exit the function - so all pointers stored to its contents are dangling and should not be used outside this function. This problem has nothing to do with the question you are trying to ask. It is the same as returning pointer to any other local variable - you should not do it. – Artemy Vysotsky Sep 05 '17 at 19:26
  • Ok, thank you both. I call C++ function which works with `wstring` from C source and I can't find out how to work with `wstring` in C. So I use `wchar_t*` as input (converting from `wchar_t*` to `wstring` is fine). Copying `wstring` content to pointer to `wchar_t*` variable works well. Thank you again. – Denis Osipov Sep 05 '17 at 19:59

0 Answers0