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

C++ 基于结构体实现矩阵转置时display函数不运行问题求解

代码BUG修复说明

核心错误点

  • 1 createMatrix函数循环上限错误
    给行指针分配内存的循环判断条件写的是i < mat->columns,但总共要分配mat->rows个行指针,该条件会导致行数值大于列数值时数组越界,触发野指针访问。
  • 2 transpose函数存在两个致命错误
    • 转置后矩阵的行列数赋值错误:转置矩阵的行数等于原矩阵的列数,列数等于原矩阵的行数,直接复用原矩阵的行列数完全不符合转置逻辑
    • 转置矩阵的data指针未分配内存就直接访问赋值,属于典型的野指针访问,会直接触发程序异常崩溃,这就是输入完元素后直接退出无输出的核心原因
  • 3 不符合「所有函数用结构体指针传参」的规则:原transpose函数是返回结构体值的写法,需要调整为传指针参数的形式

修正后完整代码

#include <iostream>
#include <iomanip>

using namespace std;

struct Matrix
{
    int **data;
    int rows;
    int columns;
};

void createMatrix(Matrix *mat)
{
    mat->data = new int *[mat->rows];
    // 修复循环上限为rows
    for (int i = 0; i < mat->rows; i++)
    {
        mat->data[i] = new int[mat->columns];
    }
}

void inputMatrix(Matrix *mat)
{
    for (int i = 0; i < mat->rows; i++)
    {
        for (int j = 0; j < mat->columns; j++)
        {
            cout << "Enter element of row " << i + 1 << " and column " << j + 1 << endl;
            cin >> mat->data[i][j];
        }
    }
}

// 修改为指针传参形式,第一个参数是原矩阵,第二个参数是转置矩阵指针
void transpose(Matrix* mat, Matrix* trans)
{
    // 修正转置矩阵行列数
    trans->rows = mat->columns;
    trans->columns = mat->rows;
    // 给转置矩阵分配内存
    createMatrix(trans);
    for (int i = 0; i < mat->rows;i++)
    {
        for(int j = 0;j<mat->columns;j++)
        {
            trans->data[j][i] = mat->data[i][j];
        }
    }
}

void display(Matrix* mat)
{
    for(int i = 0;i<mat->rows;i++)
    {
        for(int j = 0;j<mat->columns;j++)
        {
            cout<<setw(3)<<mat->data[i][j];
        }
        cout<<endl;
    }
}

// 新增内存释放函数,避免内存泄漏
void freeMatrix(Matrix* mat) {
    for (int i = 0; i < mat->rows; i++) {
        delete[] mat->data[i];
    }
    delete[] mat->data;
    mat->data = nullptr;
    mat->rows = mat->columns = 0;
}

int main()
{
    Matrix mat;
    cout<<"Enter the rows of matrix: \n";
    cin>>mat.rows;
    cout<<"\nEnter the columns of matrix: \n";
    cin>>mat.columns;

    createMatrix(&mat);
    inputMatrix(&mat);
    cout<<endl << "Original matrix:" << endl;
    display(&mat);

    Matrix trans;
    transpose(&mat, &trans);
    cout<<endl << "Transposed matrix:" << endl;
    display(&trans);
    
    // 释放内存
    freeMatrix(&mat);
    freeMatrix(&trans);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:39:04