计算二维数组对角线元素之和
关键:
将二维数组名作为实参传入计算函数中
函数中用指针遍历二维数组
/*
计算二维数组对角线元素之和
*/
#include<iostream>
using namespace std;
double trMatrix( double** matrix, int n ){
int tr;
for( int i=0; i<n; i++ ){
for( int j=0; j<n; j++){
if( i==j ){
tr += *((double*)matrix + i*n + j); // 用指针遍历二维数组
}
}
}
return tr;
}
int main(){
double matrix[3][3]={
{2,2,3},
{4,5,6},
{7,8,1}
};
cout<<trMatrix((double**)matrix, 3);
}