gpt4 book ai didi

c++ - 通过引用传递一个 wchar 数组

转载 作者:行者123 更新时间:2023-11-30 04:33:45 25 4
gpt4 key购买 nike

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

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”

谢谢 :)雷纳杜斯

最佳答案

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

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

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

关于c++ - 通过引用传递一个 wchar 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6500669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com