为什么C CHAR数据类型3D数组通过参数第一个括号为空白

Why C++ char data type 3d array when pass by parameter first bracket is blank

本文关键字:第一个 参数 空白 CHAR 数据类型 3D 数组 为什么      更新时间:2023-10-16

请查看下面的代码:

#include <iostream>
using namespace std;
int main(){
    char matrix[2][2][2];
    return 0;
}
int getMatrixData(char matrix[][2][2], int x, int y, int z) {
    return matrix[x][y][z];
}

当矩阵3D数组以参数传递到函数中时,为什么不指定第一个[]大小?如何解释这个缺失的维度?

您的代码在句法上不正确。假设您的意思是int getMatrixData(char matrix[][2][2], int x, int y, int z)

当您将数组参数传递到函数时,数组会衰减到指针到第一个元素(在这种情况下键入char [2][2])。现在,一些数组和指针的语法相似,因此您不会发现太大的区别。

当传递多维数组时,例如3D在您的情况下,可以看作是2-D数组的数组。因此,您需要在情况下给出每个元素char [2][2]的类型,并且可以跳过最终数组的尺寸,因为它无论如何都会腐烂到指针。char [2][2]是信息编译器需要计算每个元素的偏移的信息。

offset of matrix[x][y][z] = base address of matrix +
                            x * sizeof(char [2][2]) +
                            y * sizeof(char [2]) +
                            z

如果您不传递初始元素的尺寸,则编译器无法在上述方程式中解析sizeof。通过跳过的维度是可选的。

在C 中,我将以不同的方式使用多维数组。互联网上有许多主题。

此主题说明了如何使用char***进行操作。例如:

char getMatrixData(char*** matrix, int x, int y, int z)
{
    return matrix[x][y][z];
}
int main()
{
    char ***matrix = new char**[2];
    for (auto i = 0; i < 2; i++)
    {
        matrix[i] = new char*[2];
        for (auto j = 0; j < 2; j++)
        {
            matrix[i][j] = new char[2];
        }
    }
    getMatrixData(matrix, 1, 1, 1);
    // N.B.! you should normally free the memory using delete []!!
    // But in this case the program ends, so the memory is freed anyhow.
    return 0;
}

但是您也可以使用std :: vector类型

#include <vector>
using std::vector;
using CharVector1D = vector<char>;
using CharVector2D = vector<CharVector1D>;
using CharVector3D = vector<CharVector2D>;
char getMatrixData(CharVector3D const& matrix, int x, int y, int z)
{
    return matrix[x][y][z];
}
int main()
{
    CharVector3D matrix(2, CharVector2D(2, CharVector1D(2)));
    getMatrixData(matrix, 1, 1, 1);
    return 0;
}

但是,C 应该是面向对象的编程语言。因此,定义矩阵对象可能更好。

#include <vector>
using std::vector;
template <class T>
class Matrix3D
{
private:
    size_t _sizeX;
    size_t _sizeY;
    size_t _sizeZ;
    vector<T> _data;
public:
    Matrix3D(size_t const x_size, size_t const y_size, size_t const z_size)
        : _sizeX(x_size)
        , _sizeY(y_size)
        , _sizeZ(z_size)
        , _data(vector<T> (x_size*y_size*z_size))
    {}
    T GetData(size_t const x, size_t const y, size_t const z) const
    {
        return _data.at(x + (_sizeX * (y + (_sizeY * z))));
    }
};
int main()
{
    Matrix3D<char> matrix(2, 2, 2);
    matrix.GetData(1, 1, 1);
    return 0;
}