2016-12-29 16 views
0

以下はいくつかのコード例です。私は関数を直接function_2に渡す方法を知っています。私の質問は、function_1の内部にあるfunction_2に配列を渡す必要があります。また、以下に示すように、function_1にはどのようなパラメータを入れる必要があります。 私は何か助けに感謝します。C++関数内で関数を配列に渡す方法

void function_2(int ***array) 
{ 
    //do something with array 
} 

void function_1(/* what should be */) 
{ 
    function_2(/* what should be */); 
} 

int main() 
{ 
    int ***array; 
    function_2(array); 

    function_1(array); 
} 
+3

「int ***」が必要ですか?また、C++では、生の配列の代わりに 'std :: vector'や' std:array'を使うべきです。ずっと簡単です。 – crashmstr

+0

C++で配列としてint *を使用することはありません。 – SergeyA

+0

int ***はネイティブ配列と同じではありません。 –

答えて

3

あなたは直接ポインタを単に値によって渡される同じマルチレベルポインタ型を使用してそれを通過することができます。ただし、プリミティブ配列はその情報を内部的に格納しないため、配列のサイズのサイズも渡す必要があります。さもなければ、関数の内部では配列の大きさを知る方法がありません。 std::size_tは、データ構造のサイズを示すのに最適なタイプです。

ただし、これを行うべきではありません。 プリミティブ配列を使用する必要がある場合を除き、ではありません。代わりにstd::vectorを使用してください。それは内部的にサイズを格納するので、複数のパラメータを渡す必要はありません。 vectorは、他にもさまざまな改良や安全性のチェックを提供しています。これは、C++のプリミティブ配列に対する標準的な代替手段です。ここで

あなたはint型の3次元ベクトルを使用する方法である:

void function_2 
(std::vector< std::vector< std::vector<int> > > &myVector) // pass by reference 
{ 
    /* do stuff */ 
} 

void function_1 
(std::vector< std::vector< std::vector<int> > > &myVector) // pass by reference 
{ 
    function_2(myVector); 
} 

int main() 
{ 
    std::size_t pages = /* num */; 
    std::size_t cols = /* num */; 
    std::size_t rows = /* num */; 

    std::vector< std::vector< std::vector<int> > > myVector 
      (pages, std::vector< std::vector<int> >(cols, std::vector<int>(rows, 0))); 

    function_2(myVector); 

    function_1(myVector); 
} 
0

タイプint***は一貫滞在する必要があり、その関数のパラメータは1がint ***arrayであるべきであり、あなたのような機能2を呼び出す必要がありますso:function_2(array)

全コード:

void function_2(int ***array) 
{ 
    //do something with array 
} 

void function_1(int ***array) 
{ 
    function_2(array); 
} 

int main() 
{ 
    int ***array; 
    function_2(array); 

    function_1(array); 
} 
0

あなたはあなたの関数にパラメータとしてポインタを送る注意する必要があります。代わりにベクトルを使わないのはなぜですか?

std::vector<std::vector<std::vector<int>>> function_2(std::vector<std::vector<std::vector<int>>> array) 
{ 
    //do something with array 
    return array; 
} 

std::vector<std::vector<std::vector<int>>> function_1(std::vector<std::vector<std::vector<int>>> array) 
{ 
    function_2(array); 
    return array; 
} 

int main() 
{ 
    std::vector<std::vector<std::vector<int>>> array; 
    function_2(array); 
    function_1(array); 
} 
関連する問題