传递动态分配的 2D 字符数组会导致分段错误

Passing dynamically allocated 2D char array causes segmentation error?

本文关键字:分段 错误 数组 字符 动态分配 2D      更新时间:2023-10-16

>我在使用函数时遇到问题。

我有两个功能。

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;
}