我正在学习c ++中的指针,我不确定我的代码中还缺少什么。我只是想在二维数组中得到元素的总和。
这是我的代码:
#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;
}
有任何帮助吗?感谢。
答案 0 :(得分:0)
int arr[r][c];
arr的类型为int[r][c]
,无法转换为int*
您可以使用模板
template <size_t R, size_t C>
int totalRow(int(&arr)[R][C]);