分段错误从矩阵删除行

时间:2019-04-20 12:55:30

标签: c++

我试图从矩阵中删除一行,但我只会遇到分段错误,而且我不知道我的代码有什么问题。

我的代码是:

void Matriz2D::DeleteRow(int delete_row)
{

    int new_size = total_rows-1;

    int **tmp = new int * [new_size];

    for(int i = 0; i < new_size; i++){
        tmp[i] = new int [size_cols];
    }

    for(int i = 0; i < total_rows; i++){
        if(i != delete_row){
            for(int j = 0; j < toal_cols; j++){
                tmp[i][j] = data[i][j];
            }
        }
    }

    for(int i = 0; i < total_rows; i++){
        delete [] data[i];
    }

    delete [] data;
    data = tmp;

    total_rows--;
}

1 个答案:

答案 0 :(得分:0)

错误是您不检查已删除的行之后的行的索引

void Matriz2D::DeleteRow(int delete_row)
    {

        int new_size = total_rows-1;

        int **tmp = new int * [new_size];

        for(int i = 0; i < new_size; i++){
            tmp[i] = new int [size_cols];
        }

        for(int i = 0; i < total_rows; i++){
            if(i != delete_row){
                for(int j = 0; j < toal_cols; j++){
                    if (i < delete_row) {
                       tmp[i][j] = data[i][j];
                    } else {
                       tmp[i][j] = data[i-1][j];
                    }
                }
            }
        }

        for(int i = 0; i < total_rows; i++){
            delete [] data[i];
        }

        delete [] data;
        data = tmp;

        total_rows--;
    }