I am learning about pointers in c++ and I am not sure what else I am missing in my code. I am simply trying to get the sum of the the elements in a 2 dimensional array.
Here is my code:
#include <iostream>
//function prototype
int totalRow(int *arr, int row, int col);
int main(){
int r, c;
std::cout<<"How many rows in array?: ";
std::cin>>r;
std::cout<<"How many columns in array?: ";
std::cin>>c;
std::cout<<std::endl;
int arr[r][c];
for(int i=0; i<r; i++)
{
for(int e=0; e<c; e++)
{
std::cout<<"Enter arr[ "<<i+1<<"] [ "<<e+1<<" ]"<<std::endl;
std::cin>>arr[i][e];
}
}
std::cout<<totalRow(arr,r,c)<<std::endl;
return 0;
}
int totalRow(int *arr, int row, int col)
{
int sum=0;
for(int i=0; i<row; i++)
{
for(int e=0; e<col; e++)
{
sum+=*arr[i][e]; // I get an error here saying: subscripted value is
// not an array, pointer, or vector
}
}
return sum;
}
Any help? Thanks.
int arr[r][c];
The type of arr is int[r][c]
, it can't be converted to int*
You can pass the 2D array using template
template <size_t R, size_t C>
int totalRow(int(&arr)[R][C]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.