2015-05-04 33 views
0

我有一個通過向量的地址的API函數:傳遞指針的API函數

function_A() 
{    
    function_B(); 
} 

function_B() 
{ 
    vector<int> tempVector; 
    function(&tempVector[0]); // <---- API function: fills the vector with values 
    ... 
} 

tempVector創建是在function_B和它的偉大工程。

我想創建的tempVector會在function_A並傳給它一個指針,所以程序中的其他函數也會使用tempVector裏面的數據。

我試圖通過tempVectorfunction(...)幾種方式的指針,但我總是得到錯誤。

function_A() 
{   
    vector<int> tempVector; // <--- creation here 
    function_B(&tempVector); // pass its address 

    //use tempVector 
} 

function_B(vector<int> * tempVector) // receive its address 
{ 

    function(); // <---- API function: how should I pass tempVector? 
    ... 
} 
+0

你嘗試'tempVector->數據()'或'&((* tempVector)[0])'? –

+1

如果vector是空的,函數()如何填充矢量?這種不確定行爲的味道。 – rozina

回答

0

通行證它像一個指針:

function_B(vector<int> * tempVector) // receive its address 
{ 

    function(tempVector); 
    ... 
} 

function(vector<int> * tempVector) 
{ 
    ... 
} 

OR,passit作爲變量:

function_B(vector<int> * tempVector) // receive its address 
{ 

    function(*tempVector); 
    ... 
} 

function(vector<int> tempVector) 
{ 
    ... 
} 
2

爲什麼它傳遞作爲C指針,而不是作爲C++引用?

function_A() 
{   
    vector<int> tempVector; 
    function_B(tempVector); 

    //use tempVector 
} 

function_B(vector<int>& tempVector) 
{ 

    function(&tempVector[0]); 
    ... 
} 
0

你必須取消引用指針像往常一樣:

function_B(vector<int> * tempVector) { 
    function(&(*tempVector)[0]); 
}