通过引用传递wchar数组

Pass an array of wchar by reference

本文关键字:wchar 数组 引用      更新时间:2023-10-16

我想创建一个函数来为数组分配内存。假设我有这个:

PWSTR theStrings[] = { L"one", L"two", L"three" };
void foo(PWSTR a, int b) {
    a=new PWSTR[b];
    for(int i=0;i<b;i++) a[i]=L"hello";
    return;
}
int main() {
    foo(theStrings,4);
}

我的问题是,如何使函数foo和该函数的调用,以便在调用foo后,字符串将包含四个"hello"

谢谢:)Reinardus

要实现这一点,必须做两件事:

首先,必须使用动态分配的数组,而不是静态分配的数组。特别是,更改行

PSWTR theStrings[] = { L"one", L"two", L"three" };

进入

PWSTR * theString = new PWSTR[3];
theString[0] = L"one";
theString[1] = L"two";
theString[2] = L"three";

通过这种方式,您处理的指针可以修改为指向不同的内存区域,而不是使用固定内存部分的静态数组。

其次,您的函数应该使用指向指针的指针,或者引用指针。两个签名(分别)如下:

void foo(PWSTR ** a, int b); // pointer to pointer
void foo(PWSTR *& a, int b); // reference to pointer

指针选项的引用很好,因为您几乎可以使用foo:的旧代码

void foo(PWSTR *& a, int b) {
    a = new PWSTR[b];
    for(int i=0;i<b;i++) a[i]=L"hello";
}

foo的调用仍然是

foo(theStrings, 4);

所以几乎什么都不能改变。

使用指针到指针选项时,必须始终取消引用a参数:

void foo(PWST ** a, int b) {
    *a = new PWSTR[b];
    for(int i = 0; i<b; i++) (*a)[i] = L"hello";
}

并且必须使用操作员的地址调用foo

foo(&theStrings, 4);
PWSTR theStrings[] = { L"one", L"two", L"three" };
void foo(PWSTR& a, int b) {
    a=new PWSTR[b];
    for(int i=0;i<b;i++) a[i]=L"hello";
    return;
}
int main() {
    PWSTR pStrings = theStrings;
    foo(pStrings,4);
}

但相反,可以考虑使用std::vectorstd::wstring

此外,无论如何,请考虑使用函数结果(return)作为函数结果,而不是输入/输出参数。

干杯&hth。,

如果不需要使用PWSTR,则可以使用std::vector < std::string >std::valarray < std::string >

如果要存储unicode字符串(或宽字符),请将std::string替换为std::wstring

您可以在这里看到如何在CString/LLPCTSTR/PWSTR之间转换为std::string:如何在各种字符串类型之间转换。

可能会将其更改为类似的内容

void foo(PWSTR*a,int b)

foo(&ststrings,4);