[英]Passing a 2d-Array with an unknown row and column size to a function (C++)
I got this function so far : 到目前为止,我已经获得此功能:
void sumcol(int a[r][c],int r,int c){
int i,j,sum=0;
//int sizec= sizeof(a)/sizeof(a[0][0]);
//int sizer= sizeof(a)/sizeof(a[0]);
for (i=0;i<r;i++){
for (j=0;j<c;j++) sum=sum+a[j][i];
cout<<"Suma pe coloana "<<i<<" este : "<<sum<<endl;
sum=0;
}
}
I get an error on the first line that r and c were not declared in this scope. 我在第一行得到一个错误,即未在此范围内声明r和c。 Why?
为什么? Though I read right there : https://www.eskimo.com/~scs/cclass/int/sx9a.html that this is a Correct way of declaring.
尽管我在这里读到了: https : //www.eskimo.com/~scs/cclass/int/sx9a.html这是正确的声明方式。
I think your real problem is passing 2d array into function. 我认为您真正的问题是将2d数组传递给函数。 If you know your array size in compile time I will advice something like:
如果您知道编译时的数组大小,我将建议如下:
template <int r, int c>
void sumcol(int (&a)[r][c]){
int i,j,sum=0;
//int sizec= sizeof(a)/sizeof(a[0][0]);
//int sizer= sizeof(a)/sizeof(a[0]);
for (i=0;i<r;i++){
for (j=0;j<c;j++) sum=sum+a[j][i];
std::cout<<"Suma pe coloana "<<i<<" este : "<<sum<< std::endl;
sum=0;
}
}
and calling it like forexample : 并像这样调用它:
int main()
{
int temp[3][5]; // You don't forget to initialize this in your real code
sumcol(temp);
}
Or if you are using dynamiccally allocated matrix array(malloc). 或者,如果您正在使用动态分配的矩阵array(malloc)。 Than use something like:
比使用类似:
void sumcol(int** a,int r,int c){
do stuff
Consider reading this thread first Passing a 2D array to a C++ function 考虑先阅读此线程, 将2D数组传递给C ++函数
I personally find it easier to do this stuff with cool C++ Vectors instead C arrays . 我个人发现使用凉爽的C ++ Vectors而不是C数组更容易做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.