开发者

Pass an array of wchar by reference

开发者 https://www.devze.com 2023-03-16 00:00 出处:网络
I want to make a function to allocate memory to an array. Suppose I have this: PWSTR theStrings[] = { L\"one\", L\"two\", L\"three\" };

I want to make a function to allocate memory to an array. Suppose I have this:

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

My question is, how do you make the function foo and the calling of that function so that after foo is called, theStrings will contain four "hello"

Thanks :) Reinardus


There are two thing you must do to make this work:

Firstly, you must use a dynamically allocated array, rather than a statically allocated array. In particular, change the line

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

into

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

This way, you're dealing with a pointer which can be modified to point to a different region of memory, as opposed to a static array, which utilized a fixed portion of memory.

Secondly, you're function should take either a pointer to a pointer, or a reference to a pointer. The two signatures look like this (respectively):

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

The reference-to-pointer option is nice, since you can pretty much use your old code for foo:

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

And the call to foo is still

foo(theStrings, 4);

So almost nothing must be changed.

With the pointer-to-pointer option, you must always dereference the a parameter:

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

And must call foo using the address-of operator:

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

But instead of that, consider using std::vector and std::wstring and so on.

Also, anyway, consider using function result (the return) for function results, instead of in/out arguments.

Cheers & hth.,


If you are not required to use PWSTR then you can use std::vector< std::string > or std::valarray< std::string >.

If you want to store unicode strings (or wide characters) replace std::string with std::wstring.

You can see here on how to convert between CString/LPCTSTR/PWSTR to std::string: How to convert between various string types.


probably change it to something like

void foo(PWSTR * a, int b)

and

foo(&thestrings, 4);

0

精彩评论

暂无评论...
验证码 换一张
取 消