首页 > 解决方案 > Visual Studio 2017 中的读取或写入访问冲突

问题描述

我正在尝试编写一个程序,将 5*4 矩阵(中间为空)更改为 Visual Studio 2017 中的数组。例如,mat={{1,2,3,4},{5,0,0,6},{7,0,0,8},{9,0,0,10},{11,12,13,14}}更改为array={1,2,3,4,5,6,7,8,9,10,11,12,13,14}.

 // n is size of row & m is column
    void Conversion(int mat[5][4],int array[14],int n,int m) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; i < m; j++) {
                if (i == 0) {
                    array[j] = mat[i][j];;
                }
                else if ((i != 0 || i != n - 1) && (j == 0 || j == m - 1)) {
                    array[m + i - 1]= mat[i][j];
                }
                else if (i == n - 1) {
                    array[m + 2 * (n - 2) + j] = mat[i][j];
                }
            }
        }
    }

但我得到了这个:

Exception thrown: read access violation. mat was 0x1510112.

这是什么,我该怎么办?

标签: c++exception

解决方案


您混淆ij在内部for循环中导致无限循环。

最好不要使用看起来很相似的单个字母iand jor mandn以避免此类错误。特别是当他们引用的实体有更好的名称时。

我正在尝试编写一个将 5*4 矩阵(中间为空)更改为数组的程序

#include <cstddef>
#include <iostream>

void Conversion(int mat[5][4], int array[14], std::size_t num_rows, std::size_t num_cols) {
    for (std::size_t row{}, index{}; row < num_rows; ++row) {
        for (std::size_t col{}; col < num_cols; ++col) {
            if (!row || row + 1 == num_rows)
                array[index++] = mat[row][col];
            else if (!col || col + 1 == num_cols)
                array[index++] = mat[row][col];
        }
    }
}

int main()
{
    int mat[][4] = {
        { 1, 2, 3, 4 }, { 5, 0, 0, 6 }, { 7, 0, 0, 8},
        { 9, 0, 0, 10 }, { 11, 12, 13, 14 }
    };

    int arr[14];

    Conversion(mat, arr, 5, 4);

    for(auto const &i : arr)
        std::cout << i << ' ';
    std::cout.put('\n');
}

更少的分支:

void Conversion(int mat[5][4], int array[14], std::size_t num_rows, std::size_t num_cols) {
    for (std::size_t row{}, index{}; row < num_rows; ++row) {
        for (std::size_t col{}; col < num_cols; col += row && row+1 < num_rows ? num_cols-1 : 1) {
            array[index++] = mat[row][col];
        }
    }
}

更少的循环:

void Conversion(int mat[5][4], int array[14], std::size_t num_rows, std::size_t num_cols) {
    std::size_t const array_length = num_rows * num_cols - (num_rows - 2) * (num_cols - 2);
    for (std::size_t i{}; i < array_length; ++i) {
        array[i] = i < num_cols ? mat[0][i] : (i > array_length - num_cols - 1 ?
            mat[num_rows - 1][i - (array_length - num_cols)] : ((i - num_cols) % 2 ?
            mat[1 + (i - num_cols) / 2][i % 2 * num_cols - 1] : mat[1 + (i - num_cols) / 2][i % 2 * num_cols]));
    }
}

(不认真)

寻找错别字更有趣:

void Conversion(int mat[5][4], int array[14], std::size_t m, std::size_t n) {
    std::size_t const l = m*n-(m-2)*(n-2);
    for (std::size_t i{}; i<l; ++i) {
        array[i] = i<n ? mat[0][i] : (i>l-n-1 ?
            mat[m-1][i-(l-n)] : ((i-n)%2 ?
                mat[1+(i-n)/2][i%2*n-1] : mat[1+(i-n)/2][i%2*n]));
    }
}

推荐阅读