[英]c++ 2d array passing into a function
I am trying to develop a code for my thesis and for that I was trying to learn how to pass a 2D array to a function. 我正在尝试为自己的论文开发代码,并且为此,我正在尝试学习如何将2D数组传递给函数。 I wrote something.
我写点东西 The code is in the below and it is not working in this form.
该代码在下面,并且不能以这种形式工作。 I am having this error:
我遇到此错误:
error: cannot convert ‘float (*)[(((sizetype)(((ssizetype)n) + -1)) + 1)]’ to ‘float (*)[2]’ for argument ‘3’ to ‘void func(int, int, float (*)[2], float)’ func(m, n, a, omega);
When I change this matrix declaration float a[m][n]; 当我更改此矩阵声明时,float a [m] [n]; to float a[2][2] it is working.
使a [2] [2]浮动就可以了。 Thank you in advance.
先感谢您。
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;
}
}
}
Use const
for m
and n
, else you use a non-standard extension variable length array(VLA). 为
m
和n
使用const
,否则使用非标准扩展可变长度数组(VLA)。
I suggest to use std::array
which is more intuitive (or std::vector
if size is dynamic). 我建议使用更直观的
std::array
(如果大小是动态的,则使用std::array
std::vector
)。
To my understanding, the declaration 据我了解,该声明
float a[m][n]
is not possible. 不可能。 It is impossible to specify variable or constant array sizes this way.
这样无法指定可变或恒定数组大小。 The declaration as
声明为
float a[2][2]
is nicer to read if the size is actually 2 by 2, but internally it is the same as if the declaration 如果大小实际上是2乘2,则更好看,但在内部它与声明相同
float (*a)[2]
is used. 用来。 For C arrays, it it impossible to know the size after definition of the array and declaration of an array of fixed size as a parameter is impossible, at least not with the desired effect.
对于C数组,不可能在定义数组之后知道大小,并且不可能将固定大小的数组声明为参数是不可能的,至少不能达到预期的效果。
Try this :- 尝试这个 :-
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.