通过引用传递wchar数组
Pass an array of wchar by reference
我想创建一个函数来为数组分配内存。假设我有这个:
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::vector
和std::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);
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- 比较嵌套 for 循环中的两个 wchar 数组?
- 在 unicode 中将 WCHAR 数组转换为 std::string?
- 用相同的值填充了 wchar 数组元素
- 无法将QString转换为WChar数组
- 将WCHAR数组作为LPARAM发送到winproc的正确方法是什么?
- 通过引用传递wchar数组
- 使用矢量<wchar>而不是动态分配的 WCHAR 数组