c++ - 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.
这是什么,我该怎么办?
解决方案
您混淆i
并j
在内部for
循环中导致无限循环。
最好不要使用看起来很相似的单个字母i
and j
or m
andn
以避免此类错误。特别是当他们引用的实体有更好的名称时。
我正在尝试编写一个将 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]));
}
}
推荐阅读
- c# - Blazor [WASM] System.TypeLoadException:无法使用令牌 0100001a 解析类型
- java - 如何摆脱 Spark 中聚合结构对象的“col1”别名?
- python - Choroplethmapbox 渲染缓慢?
- selenium - 无法找到元素 org.openqa.selenium.NoSuchElementException:没有这样的元素:无法找到元素:{"method":"id","selector":""}
- javascript - 如何动态href链接到不同的文件夹但页面名称相同?
- python - 如何在python中设置函数参数的数据类型?
- javascript - 如何过滤地图只等于数组中的项目
- c# - 工具条删除左边框
- python - 如何终止循环进入 Python 多线程
- apache-spark - Spark Streaming 找到文件但声称找不到文件