传递动态分配的 2D 字符数组会导致分段错误
Passing dynamically allocated 2D char array causes segmentation error?
>我在使用函数时遇到问题。
我有两个功能。
createTwoDArray:提示用户输入行和列大小,创建一个新的 2D 数组并返回它,同时还修改传递给它的行和列变量。
printTwoDArray:应该采用2D数组并打印所有内容。但是,调用此函数时,会立即发生分段错误。函数内没有一行代码被调用 even。
谢谢:)
int column, row;
char** createTwoDArray(int& column, int& row) {
int min, max, i, j;
cout << "nPlease enter row size:";
cin >> i;
row = i;
cout << "nPlease enter column size:";
cin >> j;
column = j;
char** dynamicArray2 = new char*[column];
for(i = 0; i < row; i++) {
dynamicArray2[i] = new char[column];
for(j = 0; j < column; j++) {
dynamicArray2[i][j] = ' ';
}
}
return dynamicArray2;
}
void printTwoDArray(char** array, int row, int column) {
//
}
//
char** array2 = new createTwoDArray(column, row)
printTwoDArray(array2, column, row); //this causes the segmentation error
//
有两个错误:'column' 用于分配行,并且在调用 printTwoDArray(( 时行和列混淆了。
这是固定代码。它在视觉C++中运行良好。
#include "pch.h"
#include <iostream>
int column, row;
char** createTwoDArray(int& column, int& row) {
int min, max, i, j;
std::cout << "nPlease enter row size:";
std::cin >> i;
row = i;
std::cout << "nPlease enter column size:";
std::cin >> j;
column = j;
// *** Use row, not column to allocate the number of rows.
char** dynamicArray2 = new char*[row];
for (i = 0; i < row; i++) {
dynamicArray2[i] = new char[column];
for (j = 0; j < column; j++) {
dynamicArray2[i][j] = ' ';
}
}
return dynamicArray2;
}
void printTwoDArray(char** array, int row, int column) {
printf("nPrinting %d rows:nn", row);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf(" %2d", array[i][j]);
}
printf("n");
}
}
int main()
{
//
char** array2 = createTwoDArray(column, row);
// Pass row and column in the right order!
printTwoDArray(array2, row, column);
//
return 0;
}
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?