You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Stack Corruption & Wrong Multiplication Logic
    Your matrixMultiply function has two critical flaws:

    • You're incrementing arr1, arr2, and result inside the inner j loop, 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.
  2. Uninitialized Result Array
    In main, you declared int 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.

  3. Minor Readability & Useless Return Values
    The printmatrix function doesn't add newlines between rows, making output hard to parse. Also, the return values of matrixMultiply and matrixAddition are 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

  1. Safe Index Calculation
    Instead of moving pointers around (which is easy to mess up), we use i*3 + j to get the flat index of an element in a 3x3 matrix. This ensures we never write outside the array bounds.

  2. Proper Multiplication Logic
    The dot product formula is corrected: for each element result[i][j], we sum the product of elements from row i of the first matrix and column j of the second matrix. We also initialize the result array to 0 with memset to start fresh.

  3. Stack Corruption Eliminated
    We removed the incorrect pointer increments inside loops, so we only access valid memory locations.

  4. Improved Readability
    Added newlines in the print function to separate matrix rows, and changed the multiply/add functions to return void since their return values were useless.

Now when you run this, you'll get correct matrix results without any stack corruption errors!

内容的提问来源于stack exchange,提问作者user13898916

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:03:00