C++矩阵运算代码报错求助:栈溢出及计算结果异常
Hey there! Let's fix up your matrix code step by step. I see you're hitting a stack corruption error and getting garbage values for the multiplication result—let's break down what's going wrong and how to fix it.
Key Issues in Your Original Code
Stack Corruption & Wrong Multiplication Logic
YourmatrixMultiplyfunction has two critical flaws:- You're incrementing
arr1,arr2, andresultinside the innerjloop, which shoves the pointers way past the end of the arrays after the first iteration. This causes out-of-bounds writes, which is exactly what's corrupting the stack. - The multiplication formula is incorrect: matrix multiplication requires calculating the dot product of a row from the first matrix and a column from the second, not just multiplying arbitrary elements. Plus, you never initialize the result elements to 0, so you're adding to uninitialized garbage values.
- You're incrementing
Uninitialized Result Array
Inmain, you declaredint C[3][3]but didn't initialize it to 0. This means the multiplication starts adding to random garbage values, leading to those weird negative numbers in your output.Minor Readability & Useless Return Values
Theprintmatrixfunction doesn't add newlines between rows, making output hard to parse. Also, the return values ofmatrixMultiplyandmatrixAdditionare meaningless—you're returning a single element from the end of the result array, which is out of bounds after pointer increments anyway.
Fixed Full Code
#include <iostream> #include <cstring> using namespace std; void matrix(int arr[3][3]) { cout << "Matrix Input" << endl; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << "arr[" << i+1 << "][" << j+1 << "] = "; cin >> arr[i][j]; } } } void printmatrix(int arr[3][3]) { cout << "Matrix" << endl; for (int l = 0; l < 3; l++) { cout << "{ "; for (int a = 0; a < 3; a++) { cout << arr[l][a] << " "; } cout << "}" << endl; // Add newline for row separation } } void matrixMultiply(int *arr1, int *arr2, int *result) { // Initialize result to 0 to avoid garbage value accumulation memset(result, 0, 9 * sizeof(int)); for (int i = 0; i < 3; i++) { // Iterate over rows of first matrix for (int j = 0; j < 3; j++) { // Iterate over columns of second matrix for (int k = 0; k < 3; k++) { // Calculate dot product: row i of arr1 × column j of arr2 result[i * 3 + j] += arr1[i * 3 + k] * arr2[k * 3 + j]; } } } } void matrixAddition(int *arr1, int *arr2, int *result) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // Use flat index to access elements safely result[i * 3 + j] = arr1[i * 3 + j] + arr2[i * 3 + j]; } } } int main() { int A[3][3], B[3][3], C[3][3], D[3][3] = { {0,0,0},{0,0,0},{0,0,0} }; matrix(A); matrix(B); // Pass the address of the first element for clarity matrixMultiply(&A[0][0], &B[0][0], &C[0][0]); matrixAddition(&A[0][0], &B[0][0], &D[0][0]); cout << "Addition of matrix:" << endl; printmatrix(D); cout << endl << "Multiplication of matrix:" << endl; printmatrix(C); }
Breakdown of Fixes
Safe Index Calculation
Instead of moving pointers around (which is easy to mess up), we usei*3 + jto get the flat index of an element in a 3x3 matrix. This ensures we never write outside the array bounds.Proper Multiplication Logic
The dot product formula is corrected: for each elementresult[i][j], we sum the product of elements from rowiof the first matrix and columnjof the second matrix. We also initialize the result array to 0 withmemsetto start fresh.Stack Corruption Eliminated
We removed the incorrect pointer increments inside loops, so we only access valid memory locations.Improved Readability
Added newlines in the print function to separate matrix rows, and changed the multiply/add functions to returnvoidsince their return values were useless.
Now when you run this, you'll get correct matrix results without any stack corruption errors!
内容的提问来源于stack exchange,提问作者user13898916

