How can I solve the error -- error: invalid types ‘int[int]’ for array subscript?
Your function parameter ar
is a int*
. But when you wrote sum+=ar[i][j]
you're subscripting it as if we had a 2D array. You can only subscript it for one dimension like arr[i]
.
Additionally, row
and col
are not constant expressions. And in Standard C++ the size of an array must be a compile time constant(constant expression). So,
int ar[row][col]; //this statement is not standard c++
The above statement is not standard c++.
A better way(to avoid these problems) would be to use a 2D std::vector
instead of a 2D array as shown below.
#include <iostream>
#include <iomanip>
#include <vector>
//this function takes a 2D vector by reference and returns a double value
double avg(const std::vector<std::vector<int>> &arr)
{
int sum=0;
for(const std::vector<int> &tempRow: arr)
{
for(const int &tempCol: tempRow){
sum+=tempCol;
//std::cout<<sum;
}
}
return (static_cast<double>(sum)/(arr.at(0).size() * arr.size()));
}
int main()
{
int row, col;
std::cout<<"How many rows does the 2D array have: ";
std::cin>>row;
std::cout<<"How many columns does the 2D array have: ";
std::cin>>col;
//create a 2D vector instead of array
std::vector<std::vector<int>> ar(row, std::vector<int>(col));
std::cout<<"Enter the 2D array elements below : \n";
for(auto &tempRow: ar){
for(auto &tempCol: tempRow){
std::cin>>tempCol;
}
}
std::cout<<"\n Array is: \n";
for(auto &tempRow: ar)
{
for(auto &tempCol: tempRow)
std::cout<<std::setw(6)<<tempCol;
std::cout<<std::endl;
}
std::cout<<"\nAverage of all the elements of the given D array is: \n";
std::cout<<avg(ar);
return 0;
}
The output of the above program can be seen here.
The reason you are running into issues is because you are trying to dynamically allocate a 2D array (as opposed to statically).
Static allocation means before the code is even run, the values of [row] and [column] are specified.
Example: int ar[35][35]
This would create a 35x35 2D array at compile time.
Dynamic allocation means changing the values for [row] and [column] during runtime (after compiling, while running). This will require using the new
statement in C++ to create a new array of a specified size at the beginning of your function avg
. There is a lot of information about dynamic allocation of arrays in C++, such as this post here