曾经,我非常羡慕那些人见人爱的人,我也想要变成那样,可是后来我才明白人见人爱也是需要天赋的,后来我开始默默努力,我想,就算我不能让每个人都喜欢我,至少因为我做的努力能得到别人的尊重。

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

  注意,在传递三维数组作为参数时,数组的第一个[]中为空,而第二第三个不能为空。

  这样,对于大部分情况下的三维数组就可以轻松处理了。

posted @ 2018-04-15 21:47  Wayne-Zhu  阅读(5575)  评论(0编辑  收藏  举报

一分耕耘,一分收获。