下面的 printResults() 方法(从底部的 main 方法调用)为所有四个值返回 -858993460。为什么是这样?我已经用 cout 语句确认 doCalc() 方法中的数字和计算是正确的,所以我假设错误在于我使用指针和调用 printResults() 方法的方式......
typedef int matrix[2][2] ;
struct matrices {
matrix a;
matrix b;
};
...getInput() method constructs
matrix* doCalc (matrices m){
matrix toReturn;
char input;
cout << "Which calculation would you like to perform - (M)ultiply, (A)dd, (S)ubtract?";
cin >> input;
switch(input){
case 'M':
toReturn[0][0] = ((m.a[0][0])*(m.b[0][0]));
cout << "XX " << ((m.a[0][0])*(m.b[0][0]));
toReturn[0][1] = (m.a[0][1]*m.b[0][1]);
cout << "YY " << (m.a[0][1]*m.b[0][1]);
toReturn[1][0] = (m.a[1][0]*m.b[1][0]);
toReturn[1][1] = (m.a[1][1]*m.b[1][1]);
break;
case 'A':
toReturn[0][0] = (m.a[0][0]+m.b[0][0]);
toReturn[0][1] = (m.a[0][1]+m.b[0][1]);
toReturn[1][0] = (m.a[1][0]+m.b[1][0]);
toReturn[1][1] = (m.a[1][1]+m.b[1][1]);
break;
case 'S':
toReturn[0][0] = (m.a[0][0]-m.b[0][0]);
toReturn[0][1] = (m.a[0][1]-m.b[0][1]);
toReturn[1][0] = (m.a[1][0]-m.b[1][0]);
toReturn[1][1] = (m.a[1][1]-m.b[1][1]);
break;
}
return &toReturn;
}
void printResult(matrix m){
cout<<"---RESULT---\n";
cout << m[0][0] << " " << m[0][1] << "\n";
cout << m[1][0] << " " << m[1][1] << "\n";
}
void main() {
matrices m = getInput();
cout << m.a[0][0] << " " << m.a[0][1] << "\n";
cout << m.a[1][0] << " " << m.a[1][1] << "\n\n";
cout << m.b[0][0] << " " << m.b[0][1] << "\n";
cout << m.b[1][0] << " " << m.b[1][1] << "\n";
matrix* calc = doCalc(m);
matrix c = &calc;
printResult(*calc);
}