2011-06-28 17 views
0

我想做一個函數來爲數組分配內存。假設我有這樣的:通過引用傳遞一個wchar數組

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和函數的調用,使富被調用後,theStrings將包含四個「你好」

謝謝:) Reinardus

+3

使用'的std ::矢量'來代替。 –

+0

我必須使用PWSTR,因爲那些值將被傳遞到需要PWSTR數組的Windows API中 – user654894

+0

您可以使用'std :: wstring'並在適當的時候用'c_str()'解壓原始數組嗎? –

回答

2

有兩件事你必須做,以使這項工作:

首先,你必須使用動態分配的數組,而不是一個靜態分配的數組。特別地,改變線

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

哇,非常感謝你的詳細解釋...我會給它一個:) – user654894

0

如果你不使用PWSTR需要的話可以用std::vector<std::string>std::valarray<std::string>

如果要存儲unicode字符串(或寬字符),請將std::string替換爲std::wstring

你可以在這裏看到如何將CString/LPCTSTR/PWSTR轉換爲std :: string:How to convert between various string types

+0

不幸的是,我必須使用PWSTR :( – user654894

+0

但是,PWSTR a是一個指向wchar數組的指針嗎?我想要傳遞的是一個指向數組wchar的指針數組,我會給它一個鏡頭雖然 – user654894

-1

可能將其更改爲類似

無效美孚(PWSTR * A,INT B)

富(& thestrings,4);

+0

nope,它說:不能將參數1從'PWSTR(*)[3]'轉換爲'PWSTR *' – user654894

+0

foo((PWSTR **)&theStrings,4) - 抱歉沒有編譯器手動測試 –

+0

Nope ,也不起作用問題是數組是靜態分配的,並且不能改變它的大小 –

1
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::vectorstd::wstring等等。

此外,無論如何,考慮使用函數結果(return)作爲函數結果,而不是in/out參數。

乾杯&心連心,