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
into
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):
The reference-to-pointer option is nice, since you can pretty much use your old code for
foo:And the call to
foois stillSo almost nothing must be changed.
With the pointer-to-pointer option, you must always dereference the
aparameter:And must call
foousing the address-of operator: