我尝试使用函数调用更改wchar_t*
变量的值。
我使用指针(Changing an array with a function in C?),在将char*
分配给char*
或wchar_t*
到wchar_t*
时,它可以正常工作。但是,如果我尝试获取wstring
值并将其分配给wchar_t*
变量函数,则调用会产生垃圾/没有。
我尝试转换wstring
How to convert wstring to wchar_t*? C++,Convert std::wstring to WCHAR*和std::wstring to wchar_t *中讨论的内容。
代码示例:
#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);
}
输出:
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():
我的代码有什么问题以及我如何使用wchar_t*
值更改wstring
变量?
P.S。如果输出没有格式化为代码,我无法提交问题。