传递到函数中的 C++ 2D 数组
c++ 2d array passing into a function
我正在尝试为我的论文开发代码,为此我试图学习如何将 2D 数组传递给函数。我写了一些东西。代码在下面,它不能以这种形式工作。我遇到此错误:
错误:无法将参数"3"的"float (*)[((sizetype)((ssizetype)n) + -1)) + 1)]"转换为"float (*)[2]",将参数"3"转换为"void func(int, int, float (*)[2], float)" Func(m, n, a, omega);
当我更改此矩阵声明浮点数 a[m][n]; 浮点数 a[2][2] 时,它正在工作。提前谢谢你。
void func(int m1, int n1, float a1[2][2], float omeg);
using namespace std;
int main(){
int m = 2;
int n = 2;
int i, j;
float a[m][n];
float x,y,z,omega, c;
x=0.1;
y=0.2;
z=0.3;
c = 0;
omega = (x*y*z)/x;
for(j = 0; j < n; j++)
{
for(i = 0; i < m; i++)
{
a[i][j] = 0.0;
}
}
func(m, n, a, omega);
cout << a[1][0] << endl;
return 0;
}
void func(int m1, int n1, float a1[][2], float omeg)
{
for(int j = 0; j < n1; j++)
{
for(int i = 0; i < m1; i++)
{
a1[i][j] = omeg * 5;
}
}
}
使用 const
表示m
和n
,否则使用非标准扩展可变长度数组 (VLA)。
我建议使用更直观的std::array
(如果大小是动态的,则std::vector
)。
据我了解,宣言
float a[m][n]
是不可能的。不可能以这种方式指定可变或常量数组大小。声明为
float a[2][2]
如果大小实际上是 2 x 2,则更好阅读,但在内部它与声明相同
float (*a)[2]
被使用。对于 C 数组,在定义数组并将固定大小的数组声明为参数后不可能知道大小是不可能的,至少不可能达到预期的效果。
试试这个:-
int main(){
int i, j;
float a[2][2];
float x,y,z,omega, c;
x=0.1;
y=0.2;
z=0.3;
c = 0;
omega = (x*y*z)/x;
for(j = 0; j < 2; j++)
{
for(i = 0; i < 2; i++)
{
a[i][j] = 0.0;
}
}
func(a, omega);
cout << a[1][0] << endl;
return 0;
}
void func(float a1[2][2], float omeg)
{
for(int j = 0; j < 2; j++)
{
for(int i = 0; i < 2; i++)
{
a1[i][j] = omeg * 5;
}
}
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 四边形的 2D 旋转
- 打印第二列时的2d字符矢量打印空间
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 我是 C++ 的初学者,我想知道如何在 2D 矢量中获取重复值
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- opengl glBegin(GL_LINES) 和 glBegin(GL_POINT) 在 2D 中不可视化点矢量
- 在C++中迭代 2D 容器的最干净方法
- 如何引用 2D 指针?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- C++动态安全 2D 交错阵列
- 如何在C++或OpenCV子矩阵中的2D子向量上使用OpenACC?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 将 2D 推力::d evice_vector 复矩阵传递给 CUDA 内核函数