c++三維靜態數組的定義與作為函數的傳遞


  在c++中,我們可以定義三維數組,並且可以將之作為參數直接傳遞。

  定義:

#include <iostream>
#include <windows.h>
using namespace std;
const int x = 10;
const int y = 10;
const int z = 10;
int main() {
    double foo[x][y][z];
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            for (int k = 0; k < z; k++) {
                foo[i][j][k] = 1.0;
            }
        }
    }
    cout << foo[0][0][0] << endl; // 1.0
    system("pause");
    return 0;
}

  如上所示,我們設置的是靜態數組,所以必須在定義三維數組之前確定其大小,為了程序的可維護性,建議使用const int進行定義。

 

  將三維數組作為參數傳遞:

#include <iostream>
#include <windows.h>
using namespace std;
const int x = 10;
const int y = 10;
const int z = 10;
int bar(double arr[][y][z]);
int main() {
    double foo[x][y][z];
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            for (int k = 0; k < z; k++) {
                foo[i][j][k] = 1.0;
            }
        }
    }
    cout << foo[0][0][0] << endl; // 1.0
    bar(foo);
    system("pause");
    return 0;
}
int bar(double arr[][y][z]) {
    cout << "function invoked value: " << arr[1][1][1] << endl;
    return 0;
}

  如上所示,最終結果為:

1
function invoked value1

  注意,在傳遞三維數組作為參數時,數組的第一個[]中為空,而第二第三個不能為空。

  這樣,對於大部分情況下的三維數組就可以輕松處理了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM