I have written this code to calculate the average of the elements of an 2D array:
#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;
}
I am getting error while trying to access the array elements of a 2D array at line 12 -13 ar[i][j]
The error says:
error: invalid types ‘int[int]’ for array subscript
How can I solve this error?
PS: I want to give row( no. of rows in 2D array) and col(no. of columns in 2D array) in the function parameter to make this more dynamic.
int ar[row][col];isn't valid C++ because therowandcolvalues must be known at compile time.