【发布时间】:2022-01-18 04:18:07
【问题描述】:
#include <iostream>
#include <iomanip>
using namespace std;
int col=10;
int row=0;
void avg(int * ar,int row, int col)
{
float size= row * col;
int sum=0, ave;
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++){
sum+=ar[i][j];
cout<<sum;}
}
ave=sum/size;
cout<<sum<<endl;
cout<<ave;
}
int main()
{
int row, col;
cout<<"How many rows does the 2D array have: ";
cin>>row;
cout<<"How many columns does the 2D array have: ";
cin>>col;
int ar[row][col];
cout<<"Enter the 2D array elements below : \n";
for(int i=0; i<row; i++){
cout<<"For row "<<i + 1<<" : \n";
for(int j=0; j<col; j++)
cin>>ar[i][j];
}
cout<<"\n Array is: \n";
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
cout<<setw(6)<<ar[i][j];
cout<<endl;
}
cout<<"\nAverage of all the elements of the given D array is: \n";
avg((int*)ar,row,col);
return 0;
}
您好,我编写了这段代码来计算二维数组元素的平均值。尝试访问第 12 -13 行 ar[i][j]
的二维数组的数组元素时出现错误错误说-错误:数组下标的类型无效'int [int]'
我该如何解决这个错误?
PS:我想在函数参数中给出行(二维数组中的行数)和列(二维数组中的列数),以使其更具动态性。
【问题讨论】:
-
int ar[row][col];不是有效的 C++,因为row和col值必须在编译时知道。 -
到那时我能给出一些虚拟值吗?
标签: c++ arrays error-handling syntax