c++中动态分配2D数组EXC_BAD_ACCESS错误
Dynamically Allocated 2D Array EXC_BAD_ACCESS Error in C++
我在我的程序的早期阶段,现在我只是试图初始化一个2D数组来保存所有的破折号,但我一直得到一个ECX_BAD_ACCESS错误。我的代码似乎可以使用方形数组(例如:5x5或6x6),但如果我做10 × 5,我会得到错误。
void readMatrix(char **twoDarray, int &rows, int &cols)
{
std::cout << "Enter number of rows for board";
std::cin >> rows;
std::cout << "Enter number of columns for board";
std::cin >> cols;
//dynamic 2D array initialization
twoDarray = new char*[rows];
for(int i = 0; i < cols; ++i)
twoDarray[i] = new char[rows];
//set elements of array to dashes
for(int i = 0; i < rows; ++i)
for(int j = 0; j < cols; ++j){
twoDarray[i][j] = '-';
}
//printing the array
for(int i = 0; i < rows; ++i){
std::cout << " " << std::endl;
for(int j = 0; j < cols; ++j)
std::cout << twoDarray[i][j] << " ";
}
}
第一个for循环应该从0到#rows,而不是#cols。此外,在同一循环的主体中分配颜色,而不是行。
相关文章:
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- 为什么调试器引发"read access violation. this was nullptr"异常?
- 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- 使用来自 Excel VBA 的 C++ dll 时"Bad DLL calling convention" - 如何解决?
- Simulink "Access Violation"写入 C++ lambda 函数捕获列表中的 PWork 变量
- Qt QXmlStreamReader Access Violation
- "Access is Denied" U盘上的创建文件()
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- C++17 编解码器在将标准::字符串转换为标准::字符串时抛出"bad conversion"
- 例外:'Access violation reading location'
- 向量数组"Cannot access memory at address"
- Windeployqt不会运行,"Access is denied."
- 对于代理容器上的迭代器来说,"least bad implementation"可能是什么?
- 我在发布模式下运行时收到"Access violation reading location"错误 - C++
- Access C++ Enum from Swift
- Java 本机访问代码错误:"Invalid memory access"
- 获取错误:在抛出"std::bad::alloc"的实例后终止调用 what(): std::bad_alloc
- 如何获得私人会员的"read access"?
- 将数据添加到 CArray 会产生错误"cannot access private member declared in class 'CObject'"
- Bad Linux Memory Map File Performance with Random Access C++ & Python