有兩件事你必須做,以使這項工作:
首先,你必須使用動態分配的數組,而不是一個靜態分配的數組。特別地,改變線
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);
使用'的std ::矢量'來代替。 –
我必須使用PWSTR,因爲那些值將被傳遞到需要PWSTR數組的Windows API中 – user654894
您可以使用'std :: wstring'並在適當的時候用'c_str()'解壓原始數組嗎? –