为什么C CHAR数据类型3D数组通过参数第一个括号为空白
Why C++ char data type 3d array when pass by parameter first bracket is blank
请查看下面的代码:
#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;
}
相关文章:
- C++部分概念 id:显式模板规范顺序/第一个参数的特殊状态的原因是什么?
- 可变参数模板作为第一个参数
- 如何从第一个参数推断第二个参数类型?
- 候选构造函数(隐式复制构造函数)不可行:第一个参数需要 l 值
- 为什么 std::error_code 构造函数的第一个参数固定为 int
- 如何通过 std::apply 调用具有定义的第一个参数的可变参数模板函数?
- 如何获取指向 qsort 第一个参数的向量中第一项的指针?
- 如何在 Lua 回调中检测可选的第一个参数
- 如何让我的 strchr 函数同时将'const char'数组和'char'数组作为第一个参数?
- 在第一个参数上部分专用化模板
- 模板的C 功能将第一个参数设置为第二个参数为默认参数
- 如何获取指向函数第一个参数的指针
- 我可以使用use_lazy_terminal对获得3个参数懒惰的终端的第一个参数
- C++比较运算符重载中第一个参数为 null 时出现分段错误
- Cc 套接字编程 select() 的第一个参数
- 重载运算符:第一个参数对应左操作数,第二个参数对应右操作数
- 仅初始化c++11元组的第一个参数
- 我可以使用成员函数作为EnumWindows的第一个参数吗
- gdb只接受第一个参数
- 等键在 boost::unordered_multimap 中起作用:查询键是否保证是第一个参数