是否可以更改wchar_t*的内容

Is it possible to change the content of a wchar_t*?

本文关键字:wchar 是否      更新时间:2023-10-16

我有一个函数,它接收一个名为somestringwchar_t*参数。

我想调整wchar_t* somestring的大小以包含比传递的更多的元素,b因为我想复制比原始字符串更大的内容:

void a_function(wchar_t *somestring) {
    // I'd like the somestring could contain the following string:
    somestring = L"0123456789"; // this doesn't work bebause it's another pointer
}
int _tmain(int argc, _TCHAR* argv[])
{
    wchar_t *somestring = L"0123";
    a_function(somestring);
    // now I'd like the somestring could have another string at the same somestring variable, it should have the following characters: "0123456789"
}

是否可以调整wchar_t *somestring大小以包含更多字符?

正如您所发现的,void a_function(wchar_t *somestring) { somestring = L"0123456789";}只是更改局部指针变量somestring,而对调用方没有任何影响。 交换调用方的指针值需要传递指向此指针的指针:

void a_function(const wchar_t **somestring) {
  *somestring = L"0123456789";
}
int main(int argc, char* argv[]) {
    const wchar_t *somestring = L"0123";
    a_function(&somestring);
    // somestring now points to string literal L"0123456789";
}

请注意,通过覆盖指针,您将丢失对字符串文字L"0123"的引用。进一步注意,数据类型现在是const wchar_t*,因为否则不应该分配字符串文字(不允许修改字符串文字的内容(。