【问题标题】:Pass an array of wchar by reference通过引用传递一个 wchar 数组
【发布时间】:2011-06-28 01:29:27
【问题描述】:

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

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 之后,theStrings 将包含四个“hello”

谢谢 :) 雷纳杜斯

【问题讨论】:

  • 改用std::vector&lt;std::string&gt;
  • 我必须使用 PWSTR,因为这些值将被传递到需要 PWSTR 数组的 Windows API
  • 您能在适当的时候使用std::wstring 并用c_str() 解压原始数组吗?

标签: c++ visual-c++ parameter-passing pass-by-reference


【解决方案1】:

要完成这项工作,您必须做两件事:

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

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);

所以几乎什么都不需要改变。

使用pointer-to-pointer 选项,您必须始终取消引用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);

【讨论】:

  • 哇,非常感谢您的详细解释...我会试一试:)
【解决方案2】:
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)用于函数结果,而不是输入/输出参数。

干杯,

【讨论】:

    【解决方案3】:

    如果您不需要使用 PWSTR,则可以使用 std::vector&lt; std::string &gt;std::valarray&lt; std::string &gt;

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

    您可以在此处查看如何在 CString/LPCTSTR/PWSTR 与 std::string 之间进行转换:How to convert between various string types

    【讨论】:

    • 不幸的是,我必须使用 PWSTR :(
    • 但是,PWSTR a 是指向 wchar 数组的指针,不是吗?我要传递的是指向 wchar 数组的指针数组。好吧,我会试一试
    【解决方案4】:

    可能改成类似

    void foo(PWSTR * a, int b)

    foo(&thestrings, 4);

    【讨论】:

    • 不,它说:无法将参数 1 从 'PWSTR (*)[3]' 转换为 'PWSTR *'
    • foo((PWSTR**)&theStrings,4) - 抱歉没有编译器可以为你测试
    • 不,也不起作用。问题是数组是静态分配的,不能改变它的大小。
    • 你是对的,但我专注于通过引用传递数组的问题 - 我假设是伪代码而不是真实代码。
    猜你喜欢
    • 2017-08-12
    • 2011-08-09
    • 1970-01-01
    • 2020-07-30
    • 2012-04-17
    • 2014-08-06
    • 2020-03-09
    • 2019-06-29
    相关资源
    最近更新 更多